So, should be straight forward question.
Lets say I have a class with a lot of fields like:
String thizz;
long that;
boolean bar;
How can I, with reflection, see if the fields thizz, that and bar have been initialized or left to their default values of null, 0 and false?
For example, if I tried developer. age then the return value would be undefined because the developer object does not have that property name. We can check if a property exists in the object by checking if property !== undefined .
Default field values automatically insert the value of a custom field when a new record is created. You can use a default value on a formula for some types of fields or exact values, such as Checked or Unchecked for checkbox fields. After you have defined default values: The user chooses to create a new record.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.
You have only 7 primitive types and one reference type to check. If you group all Number types together, you only have four 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 == char.class && ((Character) v).charValue() == 0)
// found default value
else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
// found default value
else if(v == null)
// found default value
}
Peter Lawrey's answer works fine for me, except for fields of primitive data type char, which raises the following exception in my code :
java.lang.ClassCastException: java.lang.Character cannot be cast to java.lang.Number
So I added the char case :
Object o =
for (Field field : o.getClass().getDeclaredFields()) {
Class t = field.getType();
Object v = field.get(o);
if (boolean.class.equals(t) && Boolean.FALSE.equals(v))
// found default value
else if (char.class.equals(t) && ((Character) v) != Character.MIN_VALUE)
// found default value
else if (t.isPrimitive() && ((Number) v).doubleValue() == 0)
// found default value
else if(!t.isPrimitive() && v == null)
// found default value
}
Character.MIN_VALUE is '\u0000', which is the default value of char according to the Java Documentation on primitive data types.
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