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

前端 未结 21 2971
耶瑟儿~
耶瑟儿~ 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: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);
        }
    
    
    
    }
    

提交回复
热议问题