How to check if a field has been initialized or contains a default value in Java

I am mapping a json string to a class using jsonson mapper. The class is as follows:

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

    @JsonProperty("my_int")
    private int myInt;

    //Getters and setters
}

I want to check if the myBoolean and myInt fields are set or contain default values ​​(false and 0). I tried using reflection and checking if the field was null, but I think this will not 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.

+4
source share
2 answers

You should check if the field type is primitive, and if so, check the default value for the 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
} 

, - , . , 0, , .

+2

; .

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
}

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
}
+1

Source: https://habr.com/ru/post/1617018/


All Articles