How do I invoke a Java method when given the method name as a string?

前端 未结 21 2081
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

相关标签:
21条回答
  • 2020-11-21 05:26

    You should use reflection - init a class object, then a method in this class, and then invoke this method on an object with optional parameters. Remember to wrap the following snippet in try-catch block

    Hope it helps!

    Class<?> aClass = Class.forName(FULLY_QUALIFIED_CLASS_NAME);
    Method method = aClass.getMethod(methodName, YOUR_PARAM_1.class, YOUR_PARAM_2.class);
    method.invoke(OBJECT_TO_RUN_METHOD_ON, YOUR_PARAM_1, YOUR_PARAM_2);
    
    0 讨论(0)
  • 2020-11-21 05:26

    for me a pretty simple and fool proof way would be to simply make a method caller method like so:

    public static object methodCaller(String methodName)
    {
        if(methodName.equals("getName"))
            return className.getName();
    }
    

    then when you need to call the method simply put something like this

    //calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory 
    System.out.println(methodCaller(methodName).toString()); 
    
    0 讨论(0)
  • 2020-11-21 05:29

    This sounds like something that is doable with the Java Reflection package.

    http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html

    Particularly under Invoking Methods by Name:

    import java.lang.reflect.*;

    public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }
    
      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:29

    I do this like this:

    try {
        YourClass yourClass = new YourClass();
        Method method = YourClass.class.getMethod("yourMethodName", ParameterOfThisMethod.class);
        method.invoke(yourClass, parameter);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-11-21 05:32

    First, don't. Avoid this sort of code. It tends to be really bad code and insecure too (see section 6 of Secure Coding Guidelines for the Java Programming Language, version 2.0).

    If you must do it, prefer java.beans to reflection. Beans wraps reflection allowing relatively safe and conventional access.

    0 讨论(0)
  • 2020-11-21 05:32

    Here are the READY TO USE METHODS:

    To invoke a method, without Arguments:

    public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        object.getClass().getDeclaredMethod(methodName).invoke(object);
    }
    

    To invoke a method, with Arguments:

        public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
        }
    

    Use the above methods as below:

    package practice;
    
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    
    public class MethodInvoke {
    
        public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
            String methodName1 = "methodA";
            String methodName2 = "methodB";
            MethodInvoke object = new MethodInvoke();
            callMethodByName(object, methodName1);
            callMethodByName(object, methodName2, 1, "Test");
        }
    
        public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName).invoke(object);
        }
    
        public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
        }
    
        void methodA() {
            System.out.println("Method A");
        }
    
        void methodB(int i, String s) {
            System.out.println("Method B: "+"\n\tParam1 - "+i+"\n\tParam 2 - "+s);
        }
    }
    

    Output:

    Method A  
    Method B:  
    	Param1 - 1  
    	Param 2 - Test
    0 讨论(0)
提交回复
热议问题