getDeclaredMethod不起作用,NoSuchMethodException

我一直在尝试在Java中使用Reflection ,但它并没有很好地结束。 这是我的代码:

 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); } } 

我只是得到java.lang.NoSuchMethodException错误,我已经尝试了很多东西。 就像使用getMethod而不是getDeclaredMethod ,在getDeclaredMethod "Test"之后添加test.getClass()等等。

这是堆栈跟踪:

 java.lang.NoSuchMethodException: ReflectionTest.Test() at java.lang.Class.getDeclaredMethod(Unknown Source) at ReflectionTest.main(ReflectionTest.java:10) 

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

您在getDeclaredMethod指定了一个名称但没有参数,尽管Test方法在其签名中确实有一个参数。

尝试这个:

 Method m = test.getClass().getDeclaredMethod("Test", String.class); 

随之而来的是:

 m.invoke(test, "Cool story bro"); 

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

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

有两个问题:

问题1是你必须设想目标方法的HHS参数签名:

 Method m = test.getClass().getDeclaredMethod("Test", String.class); 

问题2是你必须将实例传递给invoke()方法:

 m.invoke(test, "Cool story bro"); 

如果方法是static可以将实例的class作为目标传递给invoke方法。

如果检查JavaDoc for Class.getDeclaredMethod(),您会发现它需要一个参数类型数组。

  final Class ContextImpl =Class.forName("android.app.ContextImpl"); Method method= ContextImpl.getDeclaredMethod("getImpl",Context.class); method.setAccessible(true); Context myContext= (Context) method.invoke(ContextImpl,getApplicationContext()); System.out.println("........... Private Method Accessed. : "+myContext);