rapadura rapadura - 14 days ago 5
Java Question

Java how can I with reflection check if a field is initialized or is default value?

So, should be straight forward question.

Lets say I have a class with alot of dumb fields like

String thizz;
long that;
Boolean bar;


How can I with reflection see if the fields thizz, that and bar have been initalized or left to their default values of null, 0 and false?

Answer

You have only 7 primitive types and one reference type to check. If you group all Number types together, you only have three values to check for.

Object o =
for (Field field : o.getClass().getDeclaredFields()) {
 Class t = field.getType();
 Object v = field.get(o);
 if(t == boolean.class && Boolean.FALSE.equals(v)) 
   // found default value
 else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
   // found default value
 else if(!t.isPrimitive() && v == null)
   // found default value
}  
Comments