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

前端 未结 2 1811
难免孤独
难免孤独 2021-01-04 12:25

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          


        
相关标签:
2条回答
  • 2021-01-04 13:02

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

    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);
    }
    
    0 讨论(0)
  • 2021-01-04 13:22

    getFields only returns public fields. If you want all fields, see getDeclaredFields

    0 讨论(0)
提交回复
热议问题