在开发中经常需要将PO、VO、DTO、DO相互转换,如果一个个set将十分麻烦,现在也有很成熟的转换工具类,例如dozer,本人日常开发也会使用这个工具。出于技痒,于是自己开始研究利用反射实现转换工具。
2020/3/10版:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 利用反射原理的对象转换类
*/
public class BeanUtils {
private static final String GET = "get";
private static final String SET = "set";
/**
* 浅复制
*
* @param from 转换对象
* @param to 目标对象
* @param <T> 返回对象
* @return
*/
public static <T> T covert(T from, T to) {
System.out.println("-----------开始转换----------");
Class<?> fromClass = from.getClass();
Class<?> toClass = to.getClass();
Method[] toClassMethods = toClass.getMethods();
//遍历to含有的方法
for (Method method : toClassMethods) {
String methodName = method.getName();
// 如果该方法是set方法
if (methodName.startsWith("set")) {
try {
// 从from 获取对应的get方法
Method getMethod = fromClass.getDeclaredMethod(methodName.replace("set", "get"));
// 执行get方法