Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    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;
like image 716
Ravi Parekh Avatar asked May 09 '11 12:05

Ravi Parekh


People also ask

Can Java reflection API access private fields?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Is Java Reflection can be used to inspect Java classes at runtime?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

How do you set a field in a reflection?

The set() method of java. lang. reflect. Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter.


2 Answers

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);
}
like image 139
Peter Lawrey Avatar answered Oct 27 '22 21:10

Peter Lawrey


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

like image 38
wjans Avatar answered Oct 27 '22 19:10

wjans