1. 自定义时间格式注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DateParse {
String format() default "yyyy-MM-dd HH:mm:ss";
}
2. 自定义数据字典注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DictParse {
String dictKey() default "none";
}
3. 定义转换方法
public static <T> T po2Vo(Object fromObj,Class<T> toCla) throws IllegalArgumentException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException{
Object toObj = toCla.newInstance();
Field[] toFields = toCla.getDeclaredFields();
for(int i = 0 ; i < toFields.length; i++){
Field f = toFields[i];
f.setAccessible(true);
String fieldName = f.getName();
Object fromVal = getValByFieldName(fromObj, fieldName);
if(fromVal != null){
if(f.isAnnotationPresent(DateParse.class)){
Date sDate = (Date)fromVal;
DateParse dataParse = f.getAnnotation(DateParse.class);
String format = dataParse.format();
if(!StringUtil.isEmpty(format)){
f.set(toObj, TimeUtil.getDateString(sDate,format));
}else{
f.set(toObj, TimeUtil.getDateTimeString(sDate));
}
}else{
String val = fromVal.toString();
f.set(toObj, val);
if(f.isAnnotationPresent(DictParse.class)){
DictParse dictParse = f.getAnnotation(DictParse.class);
String dictKey = dictParse.dictKey();
String dictText = RedisReloadUtil.getDictTextByParam(dictKey, val);
if(!StringUtil.isEmpty(dictText)){
PropertyDescriptor pd = new PropertyDescriptor(f.getName()+"Name", toCla);
Method wM = pd.getWriteMethod();
wM.invoke(toObj, dictText);
}
}
}
}
}
return (T) toObj;
}
4. 使用(在Vo中定义)
@DateParse(format = "yyyy-MM-dd")
private String createTime;
...get ... set ...
@DictParse(dictKey = "MEMBER_LEVEL")
private String level;
...get ... set ...
private String levelName;
...get ... set ...