反射——通过反射获取成员变量(属性)并使用

Field类
Class.getField(String)方法可以获取类中的指定字段(可见的),如果是私有的可以用getDecleadField(“name”)方法获取。
通过set(obj,“李四”)方法可以设置指定对象上该字段的值,如果是私有的需要先调用setAccessible(true)设置访问权限。
用获取的指定的字段调用get(boj)可以获取指定对象中该字段的值。

//创建Tercher模型
public class Tercher{
public String name;
private String homntown;
private double height;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getHometown(){
return homntown;
}
public void setHomntown(String homntown){
this.homntown=homntown;
}
public Teacher(){}
public Teacher(String name,String homntown){
super();
this.name=name;
this.homntown=homntown;
}
public Teacher(String name,double height){
super();
this.name=name;
this.height=height;
}
public String toString(){
return "Teacher[name="+"name"+",homntown="+homntown+",height="+height+"]";
}
}

//主方法
public static void main(String[] args){
//获取字节码对象
Class cls=Teacher.class;
//获取公共字段
//获取name字段,因为是私有,所以会报错,改为public
Field nameField=cls.getField("name");
//通过反射给字段赋值
Teacher teacher=new Teacher();
nameField.set(teacer,"szl");
System.out.println(teacher);

//获取私有字段
Field hometownField=cls.getDeclaredField("hometown");
//通过反射给私有属性赋值
hometown.setAccessible(true);//设置私有属性是否可以访问
hometown.set(teacher,"十堰");
System.out.println(teacher); 

//通过反射获取属性的值
Object value=hometown.get(teacher);
System.out.println(value);
}
发布了89 篇原创文章 · 获赞 0 · 访问量 1539

猜你喜欢

转载自blog.csdn.net/ShiZaolin/article/details/104264723
今日推荐