package org.dromara.common.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ClassUtils {

    public static <T, S> T copyProperties(S source, T target) throws Exception {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        Field[] sourceFields = sourceClass.getDeclaredFields();
        for (Field sourceField : sourceFields) {
            if (Modifier.isFinal(sourceField.getModifiers())){
                continue;
            }
            String fieldName = sourceField.getName();
            Field targetField = null;
            try {
                targetField = targetClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // 目标对象不存在该属性，忽略
                continue;
            }

            sourceField.setAccessible(true);
            targetField.setAccessible(true);

            Object value = sourceField.get(source);
            targetField.set(target, value);
        }

        return target;
    }

}
