java 私有成员的java反射getFields| 动态访问对象名称值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5936768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:33:07  来源:igfitidea点击:

java reflection getFields for private member| accessing object name value dynamically

javareflection

提问by Ravi Parekh

I want to print all of the class's properties with their name and values. I have used reflection, but getFieldsgive me length of 0.

我想用它们的名称和值打印所有类的属性。我使用了反射,但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

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

回答by Peter Lawrey

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

Class.getFields() 只为您提供公共字段。也许您想要 JavaBean getter?

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


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

如果要访问私有字段,可以在使用它们之前使用 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);
}

回答by wjans

getFieldsonly returns public fields. If you want all fields, see getDeclaredFields

getFields只返回公共字段。如果您想要所有字段,请参阅getDeclaredFields