欢迎来到天天文库
浏览记录
ID:18963910
大小:3.01 MB
页数:9页
时间:2018-09-27
《java se 063 反射机制大总结》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、JavaSE063反射机制大总结1、通过反射实现类对象的拷贝packagecom.javase.refelect;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;publicclassReflectTester{/***定义一个方法,完成这样一个功能,接收一个Customer类型的一个对象,然后将对象的属性拷贝出来,*生成一个新的对象,然后将新的对象拷回来。相当于实现一个对象的拷贝。**传统解决问题的方式
2、:*先有一个Customer对象,然后再去生成一个Customer对象,然后调用新生成对象的set方法,同时调用已有对象的*get方法,把get的值set到得到的新对象里面。**使用反射来实现对象的拷贝*@throwsNoSuchMethodException*@throwsSecurityException*@throwsInvocationTargetException*@throwsIllegalAccessException*@throwsInstantiationException*@throwsIllegalArgumentException*///该方法实现对C
3、ustomer对象的拷贝。即将原有对象里面的属性拷贝出来放到新的对象里面,将新对象返回来。publicObjectcopy(Objectobject)throwsSecurityException,NoSuchMethodException,IllegalArgumentException,InstantiationException,IllegalAccessException,InvocationTargetException{//获得一个类对象所对应的Class对象的第三种方式Class>classType=object.getClass();Objectobjec
4、tCopy=classType.getConstructor(newClass[]{}).newInstance(newObject[]{});/***获得对象的所有属性或成员变量*/Field[]fields=classType.getDeclaredFields();for(Fieldfield:fields){//获取属性名Stringname=field.getName();//将属性的首字母转换为大写StringfirstLetter=name.substring(0,1).toUpperCase();StringgetMethodName="get"+firstL
5、etter+name.substring(1);StringsetMethodName="set"+firstLetter+name.substring(1);//获取方法名对应的Method对象MethodgetMethod=classType.getMethod(getMethodName,newClass[]{});MethodsetMethod=classType.getMethod(setMethodName,newClass[]{field.getType()});//获取传进来的对象的现有值Objectvalue=getMethod.invoke(object,
6、newObject[]{});//将对象的值通过新对象的set方法设置进去setMethod.invoke(objectCopy,newObject[]{value});}returnobjectCopy;}publicstaticvoidmain(String[]args)throwsSecurityException,NoSuchMethodException,IllegalArgumentException,InstantiationException,IllegalAccessException,InvocationTargetException{Customercu
7、stomer=newCustomer("xiongie",23);customer.setId(1L);ReflectTesterreflectTester=newReflectTester();Customercus=(Customer)reflectTester.copy(customer);System.out.println(cus.getId()+""+cus.getName()+""+cus.getAge());}}classCustomer{privateLongid;privateStr
此文档下载收益归作者所有