有什么错误
时间: 2024-02-18 17:01:25 浏览: 29
这段代码中存在几个错误:
1. `Method dcm = c.getDeclaredMethod("work");` 这行代码缺少参数,应该是 `Method dcm = c.getDeclaredMethod("work", null);`
2. `dcm.get` 这行代码缺少参数,并且应该是 `dcm.invoke(n2, null);`
3. 在设置属性 `df.setAccessible(true);` 之前,需要先判断该属性是否是私有的,可以使用 `Modifier.isPrivate(df.getModifiers())` 进行判断。
4. 在创建 `Emp` 类的实例化时,应该使用 `Emp emp = (Emp)nc;` 进行强制类型转换。
下面是修改后的代码:
```
package g5Y29Test01;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Dmoe01 {
public static void main(String[] args) throws Exception {
//正常创建对象
Emp emp = new Emp();
emp.work();
//反射创建、
Class c = Class.forName("g5Y29Test01.Emp");
//获取所有属性
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if(Modifier.isPrivate(field.getModifiers())) {
field.setAccessible(true);
}
System.out.println(field.getType());
Thread.sleep(300);
System.out.println(field.getName());
}
//获取属性
Field df = c.getDeclaredField("name");
//创建此Class对象表示的类的一个实例化
Object nc = c.newInstance();
df.setAccessible(true);
df.set(nc,"张三");
//get
System.out.println(df.get(nc));
System.out.println("-----------------------");
//获取方法
Method dcm = c.getDeclaredMethod("work", null);
Emp emp2 = (Emp)nc;
dcm.setAccessible(true);
dcm.invoke(emp2, null);
}
}
```
相关推荐
![image/jpeg](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)