cuốn sách gpt4 ai đã làm

Java使用反射调用方法

In lại Tác giả: Walker 123 更新时间:2023-11-29 04:32:15 29 4
mua khóa gpt4 Nike

我正在尝试使用反射调用方法。

我调用的方法不是静态的,并且在我调用它的同一个类中。

我的代码的简化版本:

public class Test {
public static void main(String[] args) {
Test instance = new Test();
if (args.length > 0) {
instance.doWork(args[0]);
}
}

private void doWork(String methodName) {
Method method;

thử {
method = this.getClass().getMethod(methodName);
method.invoke(this);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
[...]
}
}

private void MethodOne() { ... };
private void MethodTwo() { ... };
[...]
private void MethodTwenty() { ... };
}

尽管包/类/方法存在,但我得到的是 java.lang.NoSuchMethodException: correct.package.and.class.MethodTwo().

谁能告诉我我做错了什么?

câu trả lời hay nhất

What I am getting is a java.lang.NoSuchMethodException: correct.package.and.class.MethodTwo()...

bạn đang gọi getMethod(),它没有返回私有(private)方法

giả thuyết arg[0] 具有正确的方法名称(否则您将再次获得 java.lang.NoSuchMethodException),2 件事必须是在这里完成:

  1. 您需要使用 getDeclaredMethod(因为 MethodOne 是私有(private)声明的)

  2. 您需要设置标志以访问它 .setAccessible(true)(这将允许您调用声明为私有(private)的方法)

ví dụ:

    Method method;
thử {
method = f.getClass().getDeclaredMethod("doThis");

method.setAccessible(true);
method.invoke(f);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
System.err.println("Opala, somethign went wrong here!");
}

关于Java使用反射调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366609/

29 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress