Search code examples
javanosuchmethoderror

getDeclaredMethod keeps giving NoSuchMethodException


I have seen some posts about the NoSuchMethodException with getDeclaredMethod but I still can't get rid of the problem.

I isolated the problem to a bare bones, can someone make this working:

public class MainMethodTest {

    public static void main(String[] args) {

        try {
            //Method m = MainMethodTest.class.getDeclaredMethod("main");
            Method m = MainMethodTest.class.getDeclaredMethod("main", MainMethodTest.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

}

Solution

  • Method m = MainMethodTest.class.getDeclaredMethod("main", MainMethodTest.class);
    

    Is trying to find main(MainMethodTest argument) method which you don't have in your code.

    If you want to get main(String[] argument) method use

    Method m = MainMethodTest.class.getDeclaredMethod("main", String[].class);