注解代码
设置某个字段的默认值为false
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DefaultValue {
boolean value();
}
通用方法
写一个通用方法来给在需要设置默认值的地方调用
package com.crossCity.common.core.utils;
import org.springframework.boot.context.properties.bind.DefaultValue;
import java.lang.reflect.Field;
public class DefaultValueProcessor {
public static void process(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(DefaultValue.class)) {
DefaultValue annotation = field.getAnnotation(DefaultValue.class);
field.setAccessible(true);
try {
if (field.get(obj) == null) {
field.set(obj, annotation.value());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
字段加上注解
@DefaultValue(false)
private boolean confirmQuantity;
最后
Goods goods=new goods();
DefaultValueProcessor.process(goods);//为空的字段设置默认值
思路是来自
java vo 注解 为空时候默认值注解-优快云博客
这位兄台,谢谢分享,我只是做一下总结