public class ReflectUtil {
public static void reflect(Object o){
//獲取參數類
Class cls = o.getClass();
//將參數類轉換為對應屬性數量的Field類型數組(即該類有多少個屬性字段 N 轉換后的數組長度即為 N)
Field[] fields = cls.getDeclaredFields();
for(int i = 0;i < fields.length; i ++){
Field f = fields[i];
f.setAccessible(true);
try {
//f.getName()得到對應字段的屬性名,f.get(o)得到對應字段屬性值,f.getGenericType()得到對應字段的類型
System.out.println("屬性名:"+f.getName()+";屬性值:"+f.get(o)+";字段類型:" + f.getGenericType());
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Student s = new Student();
s.setName("張三");
s.setAge(12);
s.setGrade(89);
reflect(s);
}
}