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.
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
}
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