自己通过反射写的一个属性copy类

Java Bean属性复制工具
本文介绍了一个用于Java Bean属性复制的实用工具类。该工具能够将一个对象的所有属性复制到另一个对象,支持自定义注解忽略指定属性的复制。通过反射机制实现,适用于Java后端开发。
package com.xxx.beancopier;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @Type BeanCopier
 * @Desc 属性copy类
 * @author
 * @date 2017-01-06
 * @Version V1.0
 */
public class BeanCopier {
    private BeanCopier() {
    }

    public static <DestType> DestType propertiesCopy(Object orig, DestType dest) {
        if (orig == null || dest == null) {
            throw new RuntimeException("参数不能为null");
        }

        Method[] destMethods = dest.getClass().getMethods();
        for (Method destMethod : destMethods) {
            if (needCopy(destMethod)) {
                MethodCopy methodCopy = new MethodCopy(destMethod);
                methodCopy.copy(orig, dest);
            }
        }
        return dest;
    }

    private static boolean needCopy(Method method) {
        PropertyCopy annotation = method.getAnnotation(PropertyCopy.class);
        if (annotation != null && annotation.ignore())
            return false;
        return method.getName().startsWith("set") && method.getParameterTypes().length == 1
                && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers());
    }

    static class MethodCopy {
        private Method method;
        private String methodName;
        private Method getterMethod;

        public MethodCopy(Method destMethod) {
            method = destMethod;
            methodName = destMethod.getName();
        }

        private void copy(Object orig, Object dest) {
            try {
                this.getterMethod = orig.getClass().getMethod("get" + methodName.substring(3));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("对象【" + orig + "】中缺失【" + methodName.replaceFirst("set", "get") + "()】方法!");
            }
            Object propertyValue = invokeMethod(orig, getterMethod);
            if (propertyValue != null) {
                invokeMethod(dest, method, propertyValue);
            }
        }

        private Object invokeMethod(Object targerObject, Method method, Object... args) {
            if (method == null) {
                throw new RuntimeException("被调用方法不能为空!");
            }
            // 验证参数数量
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length != args.length) {
                throw new RuntimeException("方法【" + method + "】的参数数量【" + parameterTypes.length + "】和反射调用时的参数数量【"
                        + args.length + "】不相符,无法完成调用!");
            }

            try {
                method.setAccessible(true);
                return method.invoke(targerObject, args);
            } catch (Throwable e) {
                throw new RuntimeException("调用对象【" + targerObject + "】的【" + method + "】方法,参数为【" + args + "】时发生异常:", e);
            }
        }

    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
@Documented
@interface PropertyCopy {
    /**
     * 被标注方法是否被忽略拷贝
     * @return
     */
    boolean ignore() default false;
}

 使用如下:

StudentDTO studentDTO1 = BeanCopier.propertiesCopy(student, new StudentDTO());

 

转载于:https://www.cnblogs.com/xlh91118/p/6277830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值