Chr*_*wes 16 java reflection variadic-functions compiler-warnings
请看下面的示例,第getMethod()一个在Eclipse中生成警告的调用.第二个不起作用,失败了NoSuchMethodException.
对于从类型调用varargs方法,
null应明确地转换类型Class<?>[]的参数.也可以将它转换为Class以进行varargs调用.getMethod(String, Class<?>...)Class<Example>
我跟着警告,没有任何工作了.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
第二个调用产生此错误:
Exception in thread "main" java.lang.NoSuchMethodException:
Example.exampleMethod(null)
at java.lang.Class.getMethod(Class.java:1605)
at Example.main(Example.java:12)
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这种行为吗?什么是避免警告的正确方法?
StK*_*ler 37
该getMethod方法的第二个参数是VarArg参数.正确的用法是:如果反射方法没有参数,则不应指定第二个参数.如果反射方法有参数,那么应该以下一个方式指定每个参数:
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
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
因此,在您的情况下,当您指定null编译器时,您不知道您指定了什么类型.当你试图把它转换null成一个未知但仍然是一个类的类时,你会得到一个例外,因为没有
public void exampleMethod(Class<?> object) { }
exampleMethod的签名.