自定义注解,进行对象属性设置
Posted yzm2008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义注解,进行对象属性设置相关的知识,希望对你有一定的参考价值。
静态工具类:
/**
* 注解字段 值重置
*
* @param dataList
* @param <T>
* @return
*/
public static <T> List<T> fieldValReset(List<T> dataList)
if (CollectionUtils.isEmpty(dataList))
return dataList;
dataList.forEach(t ->
Class clazz = t.getClass();
List<Field> fields = new ArrayList<>();
while (clazz != null)
fields.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();//获取父类字段
for (Field field : fields)
LengthLimit lengthLimit = field.getAnnotation(LengthLimit.class);
DecimalLimit decimalLimit = field.getAnnotation(DecimalLimit.class);
if (lengthLimit == null && decimalLimit == null)
continue;
try
field.setAccessible(true);
Object origVal = field.get(t);
if (null != origVal)
//length
if (null != lengthLimit)
int fieldLength = lengthLimit.length();
if (origVal instanceof String)
String val = origVal.toString();
if (val.length() > fieldLength)
field.set(t, val.substring(0, fieldLength));
else
field.set(t, val);
//decimal
if (null != decimalLimit)
int decimal = decimalLimit.decimal();
if (origVal instanceof BigDecimal)
BigDecimal bd = new BigDecimal(origVal.toString());
field.set(t, bd.setScale(decimal, BigDecimal.ROUND_HALF_UP));
catch (IllegalAccessException e)
log.error("反射解析字段属性出错:", e);
);
return dataList;
以上是关于自定义注解,进行对象属性设置的主要内容,如果未能解决你的问题,请参考以下文章