@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConvertColumn {
String field() default "";
String dictKey() default "";
}
@SneakyThrows
public static <T> void convert(T source, T target) {
Class<?> targerClass = target.getClass();
Field[] targerfields = targerClass.getDeclaredFields();
Class<?> sourceClass = source.getClass();
Field[] sourceFields = sourceClass.getDeclaredFields();
for (Field targerfield : targerfields) {
//设置允许通过反射访问私有变量
targerfield.setAccessible(true);
ConvertColumn annotation = targerfield.getAnnotation(ConvertColumn .class);
if (annotation != null) {
//获取对应字段名称
String value = annotation.field();
String dictKey = annotation.dictKey();
if(StringUtil.isNotBlank(value)) {
for (Field sourceField : sourceFields) {
sourceField.setAccessible(true);
if (sourceField.getName().equals(value)) {
//获取当前字段数据
Object data = sourceField.get(source);
if (StringUtil.isNotBlank(dictKey)) {
String dictValue = findDictConver(dictKey, String.valueOf(data));
setPropertyVal(targerfield.getName(), target, dictValue);
} else {
setPropertyVal(targerfield.getName(), target, data);
}
break;
}
}
}else{
//如果不存在字段转换,获取对应字典
if(StringUtil.isNotBlank(dictKey)){
Object data = targerfield.get(target);
String dictValue = findDictConver(dictKey, String.valueOf(data));
setPropertyVal(targerfield.getName(), target, dictValue);
}
}
}
}
}
/**
* 赋值数据
* @param propertyName
* @param target
* @param data
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static void setPropertyVal(String propertyName, Object target, Object data)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName, target.getClass());
Method setMethod = pd.getWriteMethod();
setMethod.invoke(target, data);
}
/**
* 查询字典转换数据
* @param dictKey
* @param dictValue
* @return
*/
private static String findDictConver(String dictKey, String dictValue) {
return "暂时不查询字典";
}