package com.xuli.test8;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.xuli.test5.test1;
public class Test1
{
public Object copy(Object object) throws Exception
{
Class<?> classtype = object.getClass();
//
// //方法一 获取类的实例 只能获取不带参数的的类的实例
//
// Object object2 = class1.newInstance();
//
// System.out.println(object2);
// 方法二 获取类的实例 利用构造函数
Constructor<?> constructor = classtype.getConstructor(new Class[] {});
Object object2 = constructor.newInstance(new Object[] {});// 获取constructor的一个实例
// 接下来获取属性的实例
Field[] fields = classtype.getDeclaredFields();
for (Field field : fields)
{
// System.out.println(field);
String name = field.getName();
// System.out.println(name);
String firstLetter = name.substring(0, 1).toUpperCase();
// System.out.println(firstLetter);
String getMethodname = "get" + firstLetter + name.substring(1);
// System.out.println(getMethodname);
String setMethodname = "set" + firstLetter + name.substring(1);
// System.out.println(setMethodname);
Method getMethod = classtype.getMethod(getMethodname,
new Class[] {});
Method setMethod = classtype.getDeclaredMethod(setMethodname,
field.getType());
Object value = getMethod.invoke(object, new Object[] {});
Object vaule1 = setMethod.invoke(object2, new Object[] { value });
}
return object2;
}
public static void main(String[] args) throws Exception
{
Customer customer = new Customer("Tom", 20);
customer.setId(10L);
Test1 test1 = new Test1();
Customer customer2 = (Customer) test1.copy(customer);
System.out.println(customer2);
}
}
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)
{
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;
}
}
用反射复制
代码如下