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

前端 未结 21 2102
耶瑟儿~
耶瑟儿~ 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:25

    With jooR it's merely:

    on(obj).call(methodName /*params*/).get()
    

    Here is a more elaborate example:

    public class TestClass {
    
        public int add(int a, int b) { return a + b; }
        private int mul(int a, int b) { return a * b; }
        static int sub(int a, int b) { return a - b; }
    
    }
    
    import static org.joor.Reflect.*;
    
    public class JoorTest {
    
        public static void main(String[] args) {
            int add = on(new TestClass()).call("add", 1, 2).get(); // public
            int mul = on(new TestClass()).call("mul", 3, 4).get(); // private
            int sub = on(TestClass.class).call("sub", 6, 5).get(); // static
            System.out.println(add + ", " + mul + ", " + sub);
        }
    }
    

    This prints:

    3, 12, 1

提交回复
热议问题