Konvertieren Sie die übergeordnete Entitätsklasse in eine untergeordnete Entitätsklasse

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Fqq
 * @Date: 2022/11/20
 * @Description: 将父类试题转变子类
 */
public class EntityUtil {

    private EntityUtil() {
    }

    public static <F, C> C copyFromFather(F father, C child) {

        try {
            // 判断是否是父子类关系
            if (!isExtends(father, child)) {
                throw new ClassCastException("参数异常!,非继承关系");
            }
            // 父类所有的 public 方法
            Method[] fatherMethods = father.getClass().getMethods();
            // 将所有的 get 方法储存
            Map<String, Method> fatherGetMethodMap = new HashMap<>();
            // 匹配前缀
            final String GET = "get";
            final String SET = "set";
            // 储存 get 方法
            for (Method fatherMethod : fatherMethods) {
                String methodName = fatherMethod.getName();
                if (methodName.startsWith(GET)) {
                    fatherGetMethodMap.put(methodName.substring(GET.length()), fatherMethod);
                }
            }
            // 子类所有的方法
            Method[] childMethods = child.getClass().getMethods();
            for (Method childMethod : childMethods) {
                String methodName = childMethod.getName();
                if (methodName.startsWith(SET)) {
                    String fieldName = methodName.substring(SET.length());
                    // 如果子类在父类中存在该字段的 get 方法
                    Method getMethod = fatherGetMethodMap.get(fieldName);
                    // 执行 set 操作
                    if (getMethod != null) {
                        childMethod.invoke(child, getMethod.invoke(father));
                    }
                }
            }
            return child;
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ClassCastException("实体类由父转子转化失败!");
        }
    }

    private static <F, C> boolean isExtends(F father, C child) {
        return multiExtends(father.getClass(), child.getClass());
    }

    private static boolean multiExtends(Class<?> father, Class<?> child) {
        if (child == Object.class) {
            return false;
        }
        Class<?> superclass = child.getSuperclass();
        if (superclass == father) {
            return true;
        }
        return multiExtends(father, superclass);
    }
}

Guess you like

Origin blog.csdn.net/fqqbw/article/details/127944787