Java 通過反射來獲取物件的成員變數和其值的例子
阿新 • • 發佈:2019-02-15
/**
* @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