class="java"> package com.lj.reflectionTester;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Tester
{
//该方法实现对Customer对象的拷贝操作
public Object copy( Object obj) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class<?> clz=obj.getClass();
// Constructor cons=clz.getConstructor(new Class[]{String.class, int.class});
// Object object=cons.newInstance(new Object[]{"hello",23});
Object objectCopy = clz.getConstructor(new Class[]{}).newInstance(new Object[]{});
//获得对象的所有成员变量
Field[] fields=clz.getDeclaredFields();
int i=0;
for(Field field:fields){
String name=field.getName();
String firstLetter=name.substring(0, 1).toUpperCase();
String getMethodName="get"+firstLetter+name.substring(1, name.length());
String setMethodName="set"+firstLetter+name.substring(1, name.length());
Method getMethod=clz.getMethod(getMethodName, new Class[]{});
Method setMethod=clz.getMethod(setMethodName, new Class[]{field.getType()});
Object value=getMethod.invoke(obj, new Object[]{});
setMethod.invoke(objectCopy, new Object[]{value});
System.out.println(value);
}
return objectCopy;
}
public static void main(String[] args) throws Exception
{
Tester tester=new Tester();
Customer c=(Customer) tester.copy(new Customer("li",25));
System.out.println(c.toString());
}
}
=====================Customer类===================
package com.lj.reflectionTester;
public class Customer
{
private Long id;
private String name;
private int 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;
}
public Customer(){
}
public Customer(String name, int age){
this.name=name;
this.age=age;
}
@Override
public String toString()
{
return "Customer [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}