gpt4 book ai didi

java - 反射不起作用

转载 作者:行者123 更新时间:2023-12-01 08:08:04 25 4
gpt4 key购买 nike

我是反射(reflection)新手。我面临一些错误。请帮忙。下面是我的代码:

EmployeeClass.java:

public class EmployeeClass {

private String empID;
private String empName;

public String getEmpID() {
return empID;
}

public void setEmpID(String empID) {
this.empID = empID;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public EmployeeClass(String empID, String empName) {
this.empID = empID;
this.empName = empName;
}

public String getAllDetails() {
return empID + " " + empName;
}

}

ReflectionClass.java:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionClass {

public static void main(String[] args) {

EmployeeClass emp = new EmployeeClass("1", "Emp1");
Method method = null;
try {
method = emp.getClass().getMethod("getAllDetails", null);
System.out.println(method.invoke(null, null));
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
System.out.println(e.getMessage());
}


}

}

运行 ReflectionClass.java 时,出现以下错误:

线程“main”中的异常 java.lang.NullPointerException

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at myprgs.programs.ReflectionClass.main(ReflectionClass.java:14)

最佳答案

调用invoke()时,您需要传递类的对象(包含您的方法),如下所示:

method.invoke(emp, null);

更改:

System.out.println(method.invoke(null, null));

致:

System.out.println(method.invoke(emp, null));

关于java - 反射不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19829655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com