Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getmethod returns null even though the method exists

I have the following code:

String methodName = "main";
Method[] methods = classHandle.getMethods();
for (Method m : methods)
{
    System.out.println(m.getName().equals(methodName);
}
Method classMethod = null;
try
{
    classMethod = classHandle.getMethod(methodName);
}
catch(Exception e)
{

}
System.out.println(classMethod == null);

The first print prints true, but the second one also prints true.

Why is that happening?

like image 572
John Doe Avatar asked Feb 19 '26 20:02

John Doe


1 Answers

To get hold of static void main(String [] args) use the following

classHandle.getDeclaredMethod("main", String[].class);

Possible causes (written before we knew we were after static void main)

  • Class.getMethod(name, parameters) returns only public methods, perhaps you want to use getDeclaredMethod(name, parameters) for a protected, default or private method
  • Parameters don't match. Does "main" take any parameters? The parameters passed to getDeclaredMethod() or getMethod() have to match exactly.

Consider the following.

private class Horse {
    protected void makeNoise(int level) {
    }
}

// OK
System.out.println(Horse.class.getDeclaredMethod("makeNoise", new Class<?>[]{int.class})); 

 // throws NoSuchMethodException - parameters don't match
System.out.println(Horse.class.getDeclaredMethod("makeNoise")); 

// throws NoSuchMethodException, not a public method
System.out.println(Horse.class.getMethod("makeNoise", new Class<?>[]{int.class}));
like image 166
Adam Avatar answered Feb 21 '26 14:02

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!