我的老师给了我们一些示例代码,以帮助显示Java中的反射是如何工作的,但是我收到了一些错误:
Note: DynamicMethodInvocation.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Run Code Online (Sandbox Code Playgroud)
这是代码:
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%n\n", 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我对反射一无所知,如果有人知道如何修改这段代码来编译它将非常感激.
没有编译错误,这只是一个警告.您可以忽略它,该类仍然可以正常工作.
如果要忽略这些警告,可以在方法上方添加以下内容:
@SuppressWarnings("unchecked")
Run Code Online (Sandbox Code Playgroud)
或者,您可以通过将main方法更改为:
public static void main(String[] args) {
DynamicMethodInvocation x = new DynamicMethodInvocation();
Class<?> clX = x.getClass(); // added the generic ?
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15422 次 |
| 最近记录: |