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

前端 未结 21 2163
耶瑟儿~
耶瑟儿~ 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:33
    Method method = someVariable.class.getMethod(SomeClass);
    String status = (String) method.invoke(method);
    

    SomeClass is the class and someVariable is a variable.

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

    The method can be invoked like this. There are also more possibilities (check the reflection api), but this is the simplest one:

    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    import org.junit.Assert;
    import org.junit.Test;
    
    public class ReflectionTest {
    
        private String methodName = "length";
        private String valueObject = "Some object";
    
        @Test
        public void testGetMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
                IllegalAccessException, InvocationTargetException {
            Method m = valueObject.getClass().getMethod(methodName, new Class[] {});
            Object ret = m.invoke(valueObject, new Object[] {});
            Assert.assertEquals(11, ret);
        }
    
    
    
    }
    
    0 讨论(0)
  • 2020-11-21 05:34

    This is working fine for me :

    public class MethodInvokerClass {
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {
            Class c = Class.forName(MethodInvokerClass.class.getName());
            Object o = c.newInstance();
            Class[] paramTypes = new Class[1];
            paramTypes[0]=String.class;
            String methodName = "countWord";
             Method m = c.getDeclaredMethod(methodName, paramTypes);
             m.invoke(o, "testparam");
    }
    public void countWord(String input){
        System.out.println("My input "+input);
    }
    

    }

    Output:

    My input testparam

    I am able to invoke the method by passing its name to another method (like main).

    0 讨论(0)
提交回复
热议问题