使用反射复制对象

package reflect;

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

public class InvokeTest {
    public static Object copy(Object object) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class cls = object.getClass();
        System.out.println(cls.getName());
        
        Object objectCopy = cls.getConstructor(new Class[]{}).newInstance(new Object[]{});
        
        //Field[] fields = cls.getFields();
        Field[] fields = cls.getDeclaredFields();
        for(Field field : fields) {
            System.out.println(field.getName());
            String fieldName = field.getName();
            String firstChar = fieldName.substring(0, 1).toUpperCase();
            //获得get set方法名
            String getMethodName = "get" + firstChar + fieldName.substring(1);
            String setMethodName = "set" + firstChar + fieldName.substring(1);
            //获得对应方法
            Method getMethod = cls.getMethod(getMethodName, new Class[]{});
            Method setMethod = cls.getMethod(setMethodName, new Class[]{field.getType()});
            System.out.println(getMethod.getName() + "," + setMethod.getName());
            
            //调用get方法
            Object value = getMethod.invoke(object, new Object[]{});
            //调用set方法
            setMethod.invoke(objectCopy, value);
        }
        return objectCopy;
    }
    
    public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Customer customer = new Customer(23, 1, "zhangsan");
        Customer clone = (Customer)copy(customer);
        System.out.println(clone.getId() + "," + clone.getAge() + "," + clone.getName());
    }
}


class Customer {
    private int id;
    private String name;
    private int age;
    
    public Customer(){}
    
    public Customer(int age, int id, String name) {
        super();
        this.age = age;
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    
}
原文地址:https://www.cnblogs.com/jerry19890622/p/3287148.html