反射机制首个程序

来源:互联网 发布:淘宝劲舞团徽章 编辑:程序博客网 时间:2024/05/16 07:41
import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Main {public static void main(String[] args) throws Exception{Person Criy = new Person(2010030403026L,"Criyson");refectTest test = new refectTest();System.out.println(Criy);Person CriyClone = (Person)test.copy(Criy);System.out.println(CriyClone);}}class refectTest{public Object copy(Object obj) throws Exception{Class<?> clazz = obj.getClass();//获得对象的类Constructor<?> cons = clazz.getConstructor(new Class[]{});//获得类的构造方法Object inst = cons.newInstance();//利用构造方法创建实例Field[] fields = clazz.getDeclaredFields();//获取类的所有属性for(Field field:fields){String firstChar = field.getName().substring(0,1).toUpperCase();String getterName = "get"+firstChar+field.getName().substring(1);String setterName = "set"+firstChar+field.getName().substring(1);Method getMethod = clazz.getMethod(getterName,new Class[]{});//设置getter方法,传入参数空Method setMethod = clazz.getMethod(setterName,new Class[]{field.getType()});//设置setter方法,传入对应参数Object res = getMethod.invoke(obj);//调用getter方法,获得原对象的属性值setMethod.invoke(inst,new Object[]{res});//调用setter方法,设置新对象的属性值}return inst;}}class Person{Long id;String name;public Person(){}public Person(Long id, String name) {this.id = id;this.name = name;}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;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn this.name+" "+this.id;}}

原创粉丝点击