package com.luozhihuan.reflect;import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class Reflect {

public Object copyObject(Object object) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Class<?> classType = object.getClass();

Object objcopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//Object objcopy = classType.newInstance();
Field[] fileds = classType.getDeclaredFields();

for(Field field : fileds){
String name = field.getName();

String getMethodName = "get"+name.substring(0, 1).toUpperCase()+name.substring(1);
String setMethodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);

System.out.println(getMethodName+":"+setMethodName);
Method getmethod = classType.getMethod(getMethodName, new Class<?>[]{});
Method setmethod = classType.getMethod(setMethodName, new Class<?>[]{field.getType()});
Object value = getmethod.invoke(object, new Object[]{});

setmethod.invoke(objcopy, new Object[]{value});

}
return objcopy;
} public static void main(String[] args) throws Exception {
Reflect reflect = new Reflect();
Customer customer = new Customer();
customer.setId(11L);
customer.setAge(11);
customer.setName("luo");
Customer c = (Customer)reflect.copyObject(customer);
System.out.println(c.getAge()+":"+c.getName()+":"+c.getId());
}}class Customer{

private Long id;
private String name;
private int age;

/* 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;
}
}
这是我写的一个反射机制,但是总出现NoSuchMethodException,求解