/**
* @author peter
* 2018/9/4 19:04
*/
public class Reflect {
private String name;
private int age;
private String cupSize;
public Reflect(String name, int age, String cupSize) {
this.name = name;
this.age = age;
this.cupSize = cupSize;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
}
测试
import java.lang.reflect.Field;
import java.util.Arrays;
/**
* @author peter
* 2018/9/4 19:11
*/
public class ReflectTest {
public static void main(String[] args) {
Reflect reflectTest = new Reflect("lucy", 18, "F");
Class<? extends Reflect> rtClass = reflectTest.getClass();
Field[] fields = rtClass.getDeclaredFields();//获取所有属性
Arrays.stream(fields).forEach(field -> {
//获取是否可访问
boolean flag = field.isAccessible();
try {
//设置该属性总是可访问
field.setAccessible(true);
System.out.println("成员变量"+field.getName()+"的值为:"+field.get(reflectTest));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//还原可访问权限
field.setAccessible(flag);
});
}
}
打印的结果:
成员变量name的值为:lucy
成员变量age的值为:18
成员变量cupSize的值为:F
本文介绍了一个使用Java反射机制获取对象属性值的例子。通过Reflect类创建实例,并利用反射API获取其私有字段的值。演示了如何使不可访问的字段变得可访问,以便读取其值。
1133

被折叠的 条评论
为什么被折叠?



