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.
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.
See more on this question at Stackoverflow