當前位置:編程學習大全網 - 網站源碼 - java反射獲取壹個實體類中的另外壹個實體類中屬性的值,兩個實體類是關聯關系。

java反射獲取壹個實體類中的另外壹個實體類中屬性的值,兩個實體類是關聯關系。

class Test{

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;

}

}

  • 上一篇:pico4實況釣魚音樂怎麽導入歌曲
  • 下一篇:怎樣免費做網站
  • copyright 2024編程學習大全網