getDeclaredMethod不起作用,NoSuchMethodException

Gui*_*ceU 14 java reflection

我一直在尝试Reflection在Java中使用,但它并不是很好.这是我的代码:

public class ReflectionTest {
    public static void main(String[] args) {
        ReflectionTest test = new ReflectionTest();
        try {
            Method m = test.getClass().getDeclaredMethod("Test");
            m.invoke(test.getClass(), "Cool story bro");
        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void Test(String someawesometext) {
        System.out.println(someawesometext);
    }
}
Run Code Online (Sandbox Code Playgroud)

我刚收到java.lang.NoSuchMethodException错误,我已经尝试了很多东西.比如使用getMethod而不是getDeclaredMethod,在更多test.getClass()之后添加."Test"getDeclaredMethod

这是堆栈跟踪:

java.lang.NoSuchMethodException: ReflectionTest.Test()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at ReflectionTest.main(ReflectionTest.java:10)
Run Code Online (Sandbox Code Playgroud)

我已经谷歌搜索了很多天但没有运气.所以我知道我应该怎么解决这个问题?

Nis*_*hth 27

getDeclaredMethod虽然该Test方法在其签名中有一个参数,但您可以在其中指定名称但不指定参数.

试试这个:

Method m = test.getClass().getDeclaredMethod("Test", String.class);
Run Code Online (Sandbox Code Playgroud)

随之而来:

m.invoke(test, "Cool story bro");
Run Code Online (Sandbox Code Playgroud)

因为第一个参数Method.invoke需要一个对象.但是,在静态方法的情况下,此参数将被忽略:

如果底层方法是静态的,则忽略指定的obj参数.它可能是null.