getDeclaredMethod doesn't work, NoSuchMethodException

java, reflection

Solution

You specify a name in `getDeclaredMethod` but no parameter, although the `Test` method does have a parameter in its signature.

Try this:

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

along with this:

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

Because the first argument of `Method.invoke` expects an object. However this argument is ignored in case of static methods:

If the underlying method is static, then the specified obj argument is ignored. It may be null.

Problem

I've been trying to use `Reflection` in Java, but it doesn't end up pretty well. Here's my code: ``` 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); } } ``` I just get the `java.lang.NoSuchMethodException` error, and I've tried pretty much everything. Like using `getMethod` instead of `getDeclaredMethod`, add `test.getClass()` after `"Test"` in `getDeclaredMethod` and more. Here's the stack trace: ``` java.lang.NoSuchMethodException: ReflectionTest.Test() at java.lang.Class.getDeclaredMethod(Unknown Source) at ReflectionTest.main(ReflectionTest.java:10) ``` I have been Googling for many days now but with no luck. So I does anyone know how I'm supposed to fix this?

Original source