package com.java.reflection;
import java.lang.reflect.Method;
public class ReflectTest {
public Object copyInstance(Object o) throws Exception {
// Class<?> classType = Class.forName("com.java.reflection.Customer");
Class<?> classType=o.getClass(); // 第三种获取Class对象的方式.
Method methodOfName = classType.getMethod("getName");
Method methodOfId = classType.getMethod("getId");
Method methodOfAge = classType.getMethod("getAge");
Object customer2 = classType.newInstance();
Object name = methodOfName.invoke(o);
Object id = methodOfId.invoke(o);
Object age = methodOfAge.invoke(o);
Method setMethodOfName = classType.getMethod("setName",
new Class[] { String.class });
Method setMethodOfId = classType.getMethod("setId",
new Class[] { Long.class });
Method setMethodOfAge = classType.getMethod("setAge",
new Class[] { int.class });
setMethodOfName.invoke(customer2, name);
setMethodOfId.invoke(customer2, id);
setMethodOfAge.invoke(customer2, age);
return customer2;
}
public static void main(String[] args) throws Exception {
ReflectTest test = new ReflectTest();
Customer customer1 = new Customer("PresidentXi", Long.valueOf(1000010),
65);
// Object customer2 = new Customer();
Object customer2 = test.copyInstance(customer1);
System.out.println(customer2.toString());
}
}
class Customer {
private String name;
private Long id;
private int age;
public Customer() {
}
public Customer(String name, Long id, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name is: " + name + " age is " + age + " id number is " + id;
}
}