package reflect; import java.util.*; import java.io.*; import java.lang.reflect.*; public class ReflectTester { public static void main(String[] args) { try{ Customer cus=new Customer(); cus.setAge(21); cus.setId(1l); Customer cusCopy=(Customer)copy(cus); System.out.println(cusCopy.toString()); } catch(Exception e){ System.out.println(e); } } public static Object copy(Object obj)throws Exception{ Class classType=obj.getClass(); System.out.println("Class:"+classType.getName()); //通过默认的构造方法创建一个新的对象 Object objectCopy=classType.getConstructor(new Class[]{}).newInstance(new Object[]{}); //获得对象的所有属性 Field[] fields=classType.getDeclaredFields(); for(Field field:fields){ String fieldName=field.getName(); // 如果这个成员是public修饰的,就可以用一下方法设置值 if(field.getName()=="name"){ field.set(objectCopy, "Borland Allchin"); System.out.println(field.get(objectCopy)); } String firstLetter=fieldName.substring(0,1).toUpperCase(); String getMethodName="get"+firstLetter+fieldName.substring(1); String setMethodName="set"+firstLetter+fieldName.substring(1); Method getMethod=classType.getMethod(getMethodName ,new Class[]{}); Method setMethod=classType.getMethod(setMethodName,new Class[]{field.getType()}); //调用源对象的get方法 Object value=getMethod.invoke(obj); System.out.println(fieldName+":"+value); //调用复制对象的set方法 setMethod.invoke(objectCopy,value); } return objectCopy; } } package reflect; public class Customer { private Long id; public 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; } @Override public String toString() { // return "id "+this.getId()+"name "+this.getName()+"age "+this.getAge(); } }