Please have a look at the following example, the first call to getMethod() produces a Warning in Eclipse. The second one doesn’t work and fails with a NoSuchMethodException.
The argument of type
nullshould explicitly be cast toClass<?>[]for the invocation of the varargs methodgetMethod(String, Class<?>...)from typeClass<Example>. It could alternatively be cast to Class for a varargs invocation.
I followed the warning and nothing worked anymore.
import java.lang.reflect.Method;
public class Example
{
public void exampleMethod() { }
public static void main(String[] args) throws Throwable
{
Method defaultNull = Example.class.getMethod("exampleMethod", null);
Method castedNull = Example.class.getMethod("exampleMethod", (Class<?>) null);
}
}
The second call produces this error:
Exception in thread "main" java.lang.NoSuchMethodException:
Example.exampleMethod(null)
at java.lang.Class.getMethod(Class.java:1605)
at Example.main(Example.java:12)
Can someone explain this behaviour to me? What’s the correct way to avoid the warning?
The second parameter to the
getMethodmethod is a VarArg argument.The correct use is :
If reflected method has no parameter, then no second parameter should be specified.
If the reflected method has parameter, so each parameter should be specified in the next way:
UPDATE
So, in your case, when you specify
nullthe compiler doesn’t know what type do you specify. When you try to cast thenullto a Class which is unknown but anyway is a class, you get an exception because there is nopublic void exampleMethod(Class<?> object) { }signature of exampleMethod.