您可以使用反射来遍历对象的字段并进行设置。您显然需要在类型甚至字段名称与所需的默认值之间进行某种映射,但这可以很容易地在循环中完成。例如:
for (Field f : obj.getClass().getFields()) { f.setAccessible(true); if (f.get(obj) == null) { f.set(obj, getDefaultValueForType(f.getType())); }}[更新]
使用现代Java,您可以使用注释为每个类设置字段的默认值。完整的实现可能如下所示:
// 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 Pojopublic class TestPojo extends DefaultPojo { @DefaultString("Hello world!") public String stringValue; @DefaultInteger(42); public int integerValue;}然后
TestPojo只需运行即可设置a的默认值
test.setDetaults()



