Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>for (Field f : obj.getClass().getFields()) { f.setAccessible(true); if (f.get(obj) == null) { f.set(obj, getDefaultValueForType(f.getType())); } } </code></pre> <p><strong>[Update]</strong></p> <p>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:</p> <pre><code>// 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; } </code></pre> <p>Then default values for a <code>TestPojo</code> can be set just by running <code>test.setDetaults()</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload