Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a field was initialized or contains the default value in Java

I'm mapping a json string to a class using jackson mapper. The class looks like this:

class MyClass{      
    @JsonProperty("my_boolean")
    private boolean myBoolean;

    @JsonProperty("my_int")
    private int myInt;

    //Getters and setters
}

I want to check if the fields myBoolean and myInt were actually set or contain their default values (false and 0). I tried using reflection and checking if the field was null, but I guess that won't work for primitive types. This is what I have now:

Field[] fields = myClass.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {            
                field.setAccessible(true);
                Object myObject = field.get(myClass);
                if(myObject != null) {
                  //Thought this would work, but it doesn't
                }
            }
         }

How else can I check this?

Thanks.

like image 947
drunkenfist Avatar asked Sep 26 '22 03:09

drunkenfist


2 Answers

You should check whether the field type is primitive, and if it is, check the value against a default wrapper. For example:

Map<Class, Object> defaultValues = new HashMap<Class, Object>();
defaultValues.put(Integer.class, Integer.valueOf(0)); 
// etc - include all primitive types

Then:

Object value = field.get(myClass);
if (value == null ||
    (field.getType().isPrimitive() && value.equals(defaultValues.get(field.getType())) {
   // Field has its default value
} 

That won't tell whether the field has been set or not - only whether its current value is the default value for the type. You can't tell the difference between a field which has a value of 0 because it's been explicitly set that way and one which hasn't been explicitly assigned to at all.

like image 92
Jon Skeet Avatar answered Sep 29 '22 04:09

Jon Skeet


You can also use objects with default values instead of primitive types; i.e.

class MyClass{      
    @JsonProperty("my_boolean")
    private Boolean myBoolean = BOOLEAN_DEFAULT; // get it from a map

    @JsonProperty("my_int")
    private Integer myInt = INT_DEFAULT;  // get it from a map

    //Getters and setters
}

Then

if (myClass.getMyInt() == null) {
  // The value is explicitly set to null
} else if (defaultValuesMap.get(Integer.class).equals(myClass.getMyInt())) {
  // The value has its default value
} else {
  // etc
}
like image 43
Egemen Avatar answered Sep 29 '22 05:09

Egemen