package reflectionTest1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test3Copy
{
public static void main(String[] args) throws Exception, IllegalAccessException
{
Class<Customer> cl =Customer.class;
Customer cu = cl.newInstance();
Constructor con = cl.getConstructor(new Class[]{int.class,String.class,Long.class});
Object cuCopy = con.newInstance(new Object[]{5,"hello",4L});
cu =(Customer)new Customer().Copy(cuCopy);
System.out.println(cu.getI()+","+cu.getName());
}
}
class Customer
{
private Long i;
private int age;
private String name;
public Object Copy(Object ob) throws Exception, NoSuchMethodException
{
Object obj = new Object();
Class<?> cla = obj.getClass();
//首先通过反射创建类所对应的Class类
Class<?> cl = ob.getClass();
//获取所有的属性对象
Field[] file = cl.getDeclaredFields();
//遍历属性对象进行属性值得复制
for(Field f:file)
{
String name = f.getName();
String nameFirst = name.substring(0,1).toUpperCase();
String setName = "set" + nameFirst + name.substring(1);
String getName = "get" + nameFirst + name.substring(1);
Method set = cla.getMethod(setName,new Class[]{});
Method get = cl.getMethod(getName,new Class[]{f.getType()});
Object value = get.invoke(ob,new Object[]{});
set.invoke(obj,new Object[]{value});
}
return obj;
}
public Customer(int age,String name,Long i)
{
this.age = age;
this.name = name;
this.i = i;
}
public Customer()
{
}
public Long getI()
{
return i;
}
public void setI(Long i)
{
this.i = i;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
说是标记处出问题:
Exception in thread "main" java.lang.NoSuchMethodException: java.lang.Object.setI()
at java.lang.Class.getMethod(Class.java:1605)
at reflectionTest1.Customer.Copy(Test3Copy.java:43)
at reflectionTest1.Test3Copy.main(Test3Copy.java:15) |
|