I need to make sure that no object attribute is null and add default value in case if it is null. Is there any easy way to do this, or do I have to do it manually by checking every attribute by its getters and setters?
Java Check if Object Is Null Using java. Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false.
Because local variables must be initialized in Java. In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually.
Intent. In most object-oriented languages, such as Java or C#, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references.
You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:
for (Field f : obj.getClass().getFields()) { f.setAccessible(true); if (f.get(obj) == null) { f.set(obj, getDefaultValueForType(f.getType())); } }
[Update]
With modern Java, you can use annotations to set the default values for fields on a per class basis. A complete implementation might look like this:
// DefaultString.java: import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface DefaultString { String value(); } // DefaultInteger.java: import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface DefaultInteger { int value(); } // DefaultPojo.java: import java.lang.annotation.Annotation; import java.lang.reflect.Field; public class DefaultPojo { public void setDefaults() { for (Field f : getClass().getFields()) { f.setAccessible(true); try { if (f.get(this) == null) { f.set(this, getDefaultValueFromAnnotation(f.getAnnotations())); } } catch (IllegalAccessException e) { // shouldn't happen because I used setAccessible } } } private Object getDefaultValueFromAnnotation(Annotation[] annotations) { for (Annotation a : annotations) { if (a instanceof DefaultString) return ((DefaultString)a).value(); if (a instanceof DefaultInteger) return ((DefaultInteger)a).value(); } return null; } } // Test Pojo public class TestPojo extends DefaultPojo { @DefaultString("Hello world!") public String stringValue; @DefaultInteger(42); public int integerValue; }
Then default values for a TestPojo
can be set just by running test.setDetaults()
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