本文介绍了私人成员的Java反射getFields |动态访问对象名称值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要打印类的所有属性及其名称和值.我使用了反射,但是 getFields 的长度为0.

I want to print all of the class's properties with their name and values. I have used reflection, but getFields give me length of 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

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()仅为您提供公共字段.也许您想要JavaBean吸气剂?

Class.getFields() only gives you public fields. Perhaps you wanted the JavaBean getters?

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


如果要访问私有字段,可以在使用它们之前使用getDeclaredFields()并调用field.setAccessible(true).


If you want to access the private fields, you can use getDeclaredFields() and call field.setAccessible(true) before you use them.

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);
}

这篇关于私人成员的Java反射getFields |动态访问对象名称值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 01:10