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;
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.
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.
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.
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);
}
getFields
only returns public fields. If you want all fields, see getDeclaredFields
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With