public static void main(String[] args) {
A a = new A();
System.out.println(getValueInField(a,"b1","i"));
System.out.println(getValueInField(a,"b2","i"));
System.out.println(getValueInField(a,"b3","i"));
}
public static Object getValueInField(Object obj,String field,String name){
//三個參數分別是外部的類的對象obj,作為成員屬性的類的引用名,要查詢的類內部的屬性名
try {
Object o = obj.getClass().getDeclaredField(field).get(obj);
return o.getClass().getDeclaredField(name).get(o);
} catch (Exception e) {
System.out.println("查找失敗");
return null;
}
}
}
class A{
B b1 = new B(1);
B b2 = new B(2);
}
class B{
int i;
B(int i){
this.i = i;
}
}