Java通过反射实现简单对象的拷贝

代码实现

package me.andy.practice.annotation;

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

public class ReflectUtils {

    public static Object copy(Object resource) throws Exception {
        Class<? extends Object> classType = resource.getClass();
        Object newObject = classType.newInstance();
        Field[] declaredFields = classType.getDeclaredFields();
        for (Field filed : declaredFields) {
            String firstLetter = filed.getName().substring(0, 1).toUpperCase();
            String getMethodName = "get" + firstLetter + filed.getName().substring(1);
            String setMethodName = "set" + firstLetter + filed.getName().substring(1);
            Method getMethod = classType.getMethod(getMethodName, new Class[]{});
            Method setMethod = classType.getMethod(setMethodName, new Class[]{filed.getType()});
            Object value = getMethod.invoke(resource, new Object[]{});
            setMethod.invoke(newObject, new Object[]{value});
        }
        return newObject;
    }
}


  • 代码解释

Object newObject = classType.newInstance();

等价于

Constructor<? extends Object> constructor = classType.getConstructor(new Class[]{});

Object newObject = constructor.newInstance(new Object[]{});


Field[] declaredFields = classType.getDeclaredFields()返回当前类声明的所有方法(包括私有共有)

classType.getFields()返回当前类共有方法,包括继承父类的


测试代码

package me.andy.practice.reflect;

import me.andy.practice.annotation.ReflectUtils;
import org.junit.Test;

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

import static junit.framework.Assert.assertEquals;

public class ReflectTest {

    @Test
    public void test_copy() throws Exception {
        Person person = new Person("andy", 1);
        Person copyPerson = (Person) ReflectUtils.copy(person);
        assertEquals("andy", copyPerson.getName());
        assertEquals(Integer.valueOf(1), copyPerson.getAge());
    }


}




package me.andy.practice.reflect;

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}




你可能感兴趣的:(Java通过反射实现简单对象的拷贝)