package com.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTester {
public static void main(String [] args)throws Exception{
ReflectTester reflect = new ReflectTester();
Customer customer = new Customer();
customer.setId(1L);
customer.setAge(20);
customer.setName("张三");
Customer customer2 = (Customer)reflect.copy(customer);
System.out.println(customer2.getId()+" "+customer2.getName()+" , "+customer2.getAge());
}
//该方法实现对Customer对象的拷贝操作
public Object copy(Object object) throws Exception{
//得到操作类的Class对象的第三种方式
Class<?> classType = object.getClass();
//获得操作类的Constructor对象
Constructor cons = classType.getConstructor(new Class[]{});
//用操作类对象的构造方法对象来new出一个操作类的对象。
Object obj = cons.newInstance(new Object[]{});
//得到类对象中声明的所有的成员变量
Field[] fields = classType.getDeclaredFields();
for(Field field:fields){
//得到成员变量的名称
String name = field.getName();
//截取成员变量的第一个字母,并设置成大写字母
String firstLetter = name.substring(0,1).toUpperCase();//将属性的首字母转换为答大写。
//拼凑getter方法的方法名
String getMethodName = "get"+firstLetter+name.substring(1);
//拼凑setter方法的方法名
String setMethodName = "set"+firstLetter+name.substring(1);
//根据getter的方法名利用反射机制得到Class类对象中的方法对象
Method getMethod = classType.getMethod(getMethodName, new Class[]{});
//根据setter的方法名利用反射机制得到Class类对象中的方法对象
Method setMethod = classType.getMethod(setMethodName, new Class[]{field.getType()});
//执行getter方法(调用个getter方法的对象是object)
Object value = getMethod.invoke(object, new Object[]{});
//执行setter方法(将object对象中的value值,设置到obj对象中,完成拷贝)
setMethod.invoke(obj, new Object[]{value});
}
//System.out.println(classType.getName());
System.out.println(obj);
return obj;
}
}
class Customer{
private Long id;
private String name;
private int age;
public Customer(){
}
public Customer(String name,int age){
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long 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;
}
}
java se 学习笔记 之 reflection(完成一个对象copy的demo)4
最新推荐文章于 2023-12-24 11:37:04 发布