Java反射之复制简单的JavaBean对象

时间:2022-04-24 19:05:40
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* 通过反射机制来复制JavaBean对象
* @author WalkingDog
*
*/

public class Reflect {

public static void main(String[] args) throws Exception {
Person person = new Person("walkingdog", 20);
person.setId(2009324116L);
Person personCopy = (Person)new Reflect().copy(person);
System.out.println(personCopy.getId() + " " + personCopy.getName() + " " + personCopy.getAge());
}

public Object copy(Object object) throws Exception{

//要想使用反射,首先需要获得待处理类或对象所对应的Class对象
//下面是获取Class对象的常用的3种方式
//获得运行时的类
Class<?> classType = object.getClass();
//Class<?> classType = Costomer.class;
//Class<?> classType = Class.forName("Costomer");

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

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

//以上两行代码等价于下面一行代码,newInstance()只能通过无参构造方法建立对象。
//Object objectCopy = classType.newInstance();

Field fields[] = classType.getDeclaredFields();
for(Field field : fields){
String name = field.getName();
String firstLetter = name.substring(0, 1).toUpperCase();

//获得属性的set、get的方法名
String getMethodName = "get" + firstLetter + name.substring(1);
String setMethodName = "set" + firstLetter + name.substring(1);

Method getMethod = classType.getMethod(getMethodName, new Class<?>[]{});
Method setMethod = classType.getMethod(setMethodName, new Class<?>[]{field.getType()});

//获得copy对象的属性值
Object value = getMethod.invoke(object, new Object[]{});

//设置被copy对象的属性值
setMethod.invoke(objectCopy, value);
}
return objectCopy;
}
}

//JavaBean
class Person{
private Long id;
private String name;
private int age;

//每个JavaBean都应该实现无参构造方法
public Person() {}

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

//setter、getter方法
}