我的老师给了我们一些示例代码,以帮助我们展示Java中的反射是如何工作的。然而,我遇到了一些错误:
Note: DynamicMethodInvocation.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
这是代码:
import java.lang.reflect.*;
import java.lang.Class;
import static java.lang.System.out;
import static java.lang.System.err;
public class DynamicMethodInvocation {
public void work(int i, String s) {
out.printf("Called: i=%d, s=%s%nn", i, s);
}
public static void main(String[] args) {
DynamicMethodInvocation x = new DynamicMethodInvocation();
Class clX = x.getClass();
out.println("class of x: " + clX + 'n');
// To find a method, need array of matching Class types.
Class[] argTypes = { int.class, String.class };
// Find a Method object for the given method.
Method toInvoke = null;
try {
toInvoke = clX.getMethod("work", argTypes);
out.println("method found: " + toInvoke + 'n');
} catch (NoSuchMethodException e) {
err.println(e);
}
// To invoke the method, need the invocation arguments, as an Object array
Object[] theArgs = { 42, "Chocolate Chips" };
// The last step: invoke the method.
try {
toInvoke.invoke(x, theArgs);
} catch (IllegalAccessException e) {
err.println(e);
} catch (InvocationTargetException e) {
err.println(e);
}
}
}
我对反射一无所知,如果有人知道我如何修改这段代码来编译它,我将不胜感激。
没有编译错误,这只是一个警告。你可以忽略这一点,类仍然可以正常工作。
如果你想忽略这些警告,你可以在你的方法上面添加以下内容:
@SuppressWarnings("unchecked")
或者,您可以通过将主要方法更改为:来解决此问题
public static void main(String[] args) {
DynamicMethodInvocation x = new DynamicMethodInvocation();
Class<?> clX = x.getClass(); // added the generic ?
...
}
Note: Recompile with -Xlint:unchecked for details.
javac -Xlint:unchecked filename.java
它将显示未检查的所有异常,这些异常必须通过用户定义或系统定义的异常代码捕获