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
null
should 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 getMethod
method 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:
import java.lang.reflect.Method;
public class Example {
public void exampleMethodNoParam() {
System.out.println("No params");
}
public void exampleMethodWithParam(String arg) {
System.out.println(arg);
}
public static void main(String[] args) throws Throwable {
Example example = new Example();
Method noParam = Example.class.getMethod("exampleMethodNoParam");
Method stringParam = Example.class.getMethod("exampleMethodWithParam", String.class);
noParam.invoke(example);
stringParam.invoke(example, "test");
//output
//No params
//test
}
}
UPDATE
So, in your case, when you specify null
the compiler doesn't know what type do you specify. When you try to cast the null
to a Class which is unknown but anyway is a class, you get an exception because there is no
public void exampleMethod(Class<?> object) { }
signature of exampleMethod.
The getMethod defined in java API is:
Method java.lang.Class.getMethod(String name, Class<?>... parameterTypes)
If the method you called has no arguments,then you should supply a empty array or a array with 0 length for the second argument.like this:
Method defaultNull = Example.class.getMethod("exampleMethod", new Class<?>[0]);
Invoke the method you should also set a empty array.
defaultNull.invoke(example , new Object[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With