java reflection getfields for private member|动态访问对象名称值

2022-09-05 00:25:19

我想打印类的所有属性及其名称和值。我用了反射,但给我的长度为0。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();
            }
}

汇率代码.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

Class.getFields() 只给你公共字段。也许你想要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)。

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

答案 2

getFields仅返回公共字段。如果需要所有字段,请参阅获取声明字段