Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

后端 未结 8 504
天涯浪人
天涯浪人 2020-12-05 06:57

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 checkin

8条回答
  •  Happy的楠姐
    2020-12-05 07:31

    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()

提交回复
热议问题