Java reflection: getMethod(String method, Object[].class) not working

前端 未结 3 1930
囚心锁ツ
囚心锁ツ 2021-01-02 02:58

I have the following code:

public void myMethod(Object... args) {
    System.out.println(\"this is myMethod\");
}

public void invokeMyMethod() {
    Method          


        
3条回答
  •  误落风尘
    2021-01-02 02:59

    You can use dp4j command-line to answer your question:

        $ javac -cp ../dp4j-1.2-SNAPSHOT-jar-with-dependencies.jar -All -Averbose=true MyClass.java
    MyClass.java:7: Note: 
    public class MyClass {
    
    public MyClass() {
        super();
    }
    
    public void myMethod(Object... args) {
        System.out.println("this is myMethod");
    }
    
    @com.dp4j.Reflect()
    public void invokeMyMethod() throws java.lang.ClassNotFoundException, java.lang.NoSuchFieldException, java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, java.lang.IllegalArgumentException {
        final java.lang.reflect.Method myMethodWithArrayMethod = Class.forName("MyClass").getDeclaredMethod("myMethod", .java.lang.Object[].class);
        myMethodWithArrayMethod.setAccessible(true);
        myMethodWithArrayMethod.invoke(this, new .java.lang.Object[1][]{new .java.lang.Object[2][]{"hi", "there"}});
    }
    
    public static void main(String... args) throws Exception {
        new MyClass().invokeMyMethod();
    }
    }
    public void invokeMyMethod() {
                ^
    
    $ java MyClass
    this is myMethod
    

提交回复
热议问题