Entity与Entity之间的相互转化

爱⌒轻易说出口 提交于 2020-01-14 20:06:29

一。两个实体类的属性名称对应之间的转化

1.两个实体类

public class Entity1 {
    
    private Integer id;
    private String name;
    private Integer age;
    private byte sex;
       // get/set
}

public class Entity2 {
    private String name;
    private Double sal;
    private Integer age;
        // get/set
}

2。Entity2Entity 转化类

public class Entity2Entity {
    public static void main(String[] args) throws Exception {
        Entity1 en = new Entity1(1, "zcj", 18, (byte)1);
        Object parse = parse(en,new Entity2());
        System.out.println(parse);
    }
    
    public static <T, F> F parse(T src, F target) throws Exception{
        Method[] srcMethods = src.getClass().getMethods();
        Method[] targetMethod = target.getClass().getMethods();
        for(Method m : srcMethods) {
            if(m.getName().startsWith("get")) {
                Object result = m.invoke(src);
                for(Method mm : targetMethod) {
                    if(mm.getName().startsWith("set") && mm.getName().substring(3).
                            equals(m.getName().substring(3))) {
                        mm.invoke(target,result);
                    }
                }
            }
        }
        return target;
    }

}

3。运行结果

PersonDto [personId=1, personName=zcj, personAge=12, sal=12.0]

  

二。基于实体类中要转化的get方法或者属性进行转化

package com.entity.demo3;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.entity.demo.Entity1;
import com.entity.demo.Entity2;

public class EntityUtil {
    
    public static void main(String[] args) {
        Entity1 src = new Entity1(1, "zcj", 18, (byte)1);
        Entity2 target = new Entity2();
//        target = entity2entityByMethod(src,target);
        target = entity2entityByField(src,target);
        System.out.println(target);
    }

    // 首字母转大写
    public static String firstChartToUpper(String str) {
        if (Character.isUpperCase(str.charAt(0))) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        return sb.append(Character.toUpperCase(str.charAt(0))).append(str.substring(1)).toString();
    }

    /**
     * 基于实体类中要转化的get方法获取
     * @param src
     * @param target
     * @return
     */
    public static <T, F> F entity2entityByMethod(T src, F target) {
        Field[] targetFields = target.getClass().getDeclaredFields();
        for (Field field : targetFields) {
            try {
                Method method = src.getClass().getMethod("get" + firstChartToUpper(field.getName()));
                Object value = method.invoke(src);
                field.setAccessible(true);
                field.set(target, value);
            } catch (Exception e) {
                continue;
            }
        }
        return target;
    }
    
    /**
     * 基于实体类中属性进行转换
     * @param src
     * @param target
     * @return
     */
    public static <T, F> F entity2entityByField(T src, F target) {
        Field[] srcFields = src.getClass().getDeclaredFields();
        Class<? extends Object> class1 = target.getClass();
        for (Field field : srcFields) {
            try {
                field.setAccessible(true);
                Object value = field.get(src);
                if(value == null) {
                    continue;
                }
                Method mm = class1.getMethod("set"+firstChartToUpper(field.getName()),value.getClass());
                mm.invoke(target, value);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return target;
    }

}

三。利用反射+注解进行转化

1.两个实体类

public class Pseron {
	private String perId;
	private String perName;
	private String perAge;
	private Double sal;
	private Integer pno;
}

public class PersonDto {
	@RelMapper(value="perId")
	private String personId;
	@RelMapper(value="perName")
	private String personName;
	@RelMapper(value="perAge")
	private String personAge;
	private Double sal;
}

2.一个自定义的注解

//Target 注解的使用域,FIELD表示使用在属性上面,TYPE表示使用在类上面
@Target({ElementType.FIELD,ElementType.TYPE}) 
//Retention 设置注解的生命周期 ,这里定义为RetentionPolicy.RUNTIME 非常关键
@Retention(RetentionPolicy.RUNTIME) 
@Documented
public @interface Mapper {
    //自定义属性
    String value() default ""; 
}

3.转化类

public class Entity2Dto {
    public static void main(String[] args){
        Object en2Dto = en2Dto(new Pseron("1","zcj", "12",12.0,null), new PersonDto());
        System.out.println(en2Dto);
    }
    
    public static Object en2Dto(Object src,Object target) {
        Field[] targetFields = target.getClass().getDeclaredFields();
        Class<? extends Object> srcFields = src.getClass();
        String name;
        for (Field field : targetFields) {
            try {
                field.setAccessible(true);
                // 判断这个字段上是否有相应的注解信息(RelMapper.class)
                if(field.isAnnotationPresent(Mapper.class)){
                    Mapper annotation = field.getAnnotation(Mapper.class);
                    name = annotation.value();
                }else {
                    name = field.getName();
                }
                Field field2 = srcFields.getDeclaredField(name);
                if(field2 != null) {
                    field2.setAccessible(true);
                }
                Object object = field2.get(src);
                field.set(target, object);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return target;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!