通过java反射技术访问类中私有成员属性

来源:互联网 发布:云管理平台软件 编辑:程序博客网 时间:2024/04/20 04:17
package com.huishao.entity;


public class student {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public student(String name, String id) {
super();
this.name = name;
this.id = id;
System.out.println("有参构造函数创造对象");
}
public student(){
System.out.println("无参构造函数创建对象");
}

}

==========================================================================

/**
* 通过反射技术访问类的私有成员

* @throws Exception
*/
@Test
public void test04() throws Exception {
Class<?> forName = Class.forName("com.huishao.entity.student");
Object newInstance = forName.newInstance();
student s = (student) newInstance;
Field declaredField = forName.getDeclaredField("name");
//允许访问私有成员
declaredField.setAccessible(true);
declaredField.set(newInstance, "张三");
System.out.println(s.getName());
}

阅读全文
0 0
原创粉丝点击