sách gpt4 ai đã đi

java - .java 使用未经检查或不安全的操作。注: Recompile with -Xlint:unchecked for details

In lại 作者:行者123 更新时间:2023-12-02 14:11:26 28 4
mua khóa gpt4 Nike

我的老师给了我们一些示例代码来帮助展示 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%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;
thử {
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.
thử {
toInvoke.invoke(x, theArgs);
} catch (IllegalAccessException e) {
err.println(e);
} catch (InvocationTargetException e) {
err.println(e);
}
}
}

我对反射一无所知,如果有人知道我如何修改这段代码以使其编译,我将非常感激。

1 Câu trả lời

没有编译错误,这只是一个警告。您可以忽略这一点,该类仍然可以正常工作。

如果您想忽略这些警告,可以在您的方法上方添加以下内容:

  @SuppressWarnings("unchecked")

或者,您可以通过将 main 方法更改为来解决此问题:

public static void main(String[] args) {
DynamicMethodInvocation x = new DynamicMethodInvocation();

Class clX = x.getClass(); // added the generic ?
...
}

关于java - .java 使用未经检查或不安全的操作。注: Recompile with -Xlint:unchecked for details,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307801/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com