我想打印类的所有属性及其名称和值。我使用了反射,但是getFields
给了我0的长度。
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;
最佳答案
Class.getFields()仅为您提供公共(public)字段。也许您想要JavaBean setter/getter ?
BeanInfo info = Introspector.getBeanInfo(getMaxRateCode.getClass());
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println(pd.getName()+": "+pd.getReadMethod().invoke(getMaxRateCode));
如果要访问私有(private)字段,则可以使用getDeclaredFields()并在使用它们之前调用field.setAccessible(true)。
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);
}
关于私有(private)成员的Java反射getFields |动态访问对象名称值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5936768/