2011-05-09 75 views
10

我想打印所有類的屬性及其名稱和值。我已經使用反射,但getFields給我0針對私有成員的java反射getFields動態訪問對象名稱值

RateCode getMaxRateCode = instance.getID(Integer.parseInt((HibernateUtil 
      .currentSession().createSQLQuery("select max(id) from ratecodes") 
      .list().get(0).toString()))); 
for (Field f : getMaxRateCode.getClass().getFields()) { 
      try { 
       System.out.println(f.getGenericType() + " " + f.getName() + " = " 
         + f.get(getMaxRateCode)); 
      } catch (IllegalArgumentException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IllegalAccessException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
} 

RateCode.java

private Integer rateCodeId; 
    private String code;  
    private BigDecimal childStay;  
    private DateTime bookingTo; 
    private Short minPerson;  
    private Boolean isFreeNightCumulative = false; 
    private boolean flat = false; 
    private Timestamp modifyTime; 
+1

你的'RateCode'看起來像什麼? – asgs 2011-05-09 12:21:12

+0

你去了。你的領域沒有一個是「公共」的。見@彼得的答案。 – asgs 2011-05-09 12:26:37

回答

19

Class.getFields()只給你的公共字段的長度。也許你想要JavaBean獲得者?

BeanInfo info = Introspector.getBeanInfo(getMaxRateCode.getClass()); 
for (PropertyDescriptor pd : info.getPropertyDescriptors()) 
    System.out.println(pd.getName()+": "+pd.getReadMethod().invoke(getMaxRateCode)); 

如果你想進入的是私人領域,你可以使用getDeclaredFields()並調用field.setAccessible(真)然後再使用它們。

for (Field f : getMaxRateCode.getClass().getDeclaredFields()) { 
    f.setAccessible(true); 
    Object o; 
    try { 
     o = f.get(getMaxRateCode); 
    } catch (Exception e) { 
     o = e; 
    } 
    System.out.println(f.getGenericType() + " " + f.getName() + " = " + o); 
} 
+0

是的我所有的領域都有私人訪問。 – 2011-05-09 12:25:55

+0

使用屬性可以訪問任何公共getter。如果你想查看底層字段,最好的方法是使用IDE的調試器,並在產生結果的地方放置一個斷點。 – 2011-05-09 12:39:28

+0

你正確的IDE,但我想打印這個,我有getter/setter,因爲你都準備好說了。 thanx例如。 – 2011-05-09 12:56:03

13

getFields只返回公共字段。如果你想要所有的領域,請參閱getDeclaredFields

+1

甚至繼承的http://stackoverflow.com/a/2405757/1422630 – 2015-03-04 08:09:25

+0

所有的答案應該是這樣的。 :d – milosmns 2015-10-01 22:34:07