Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getDeclaredMethod doesn't work, NoSuchMethodException

Tags:

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?