java se 063 反射机制大总结

java se 063 反射机制大总结

ID:18963910

大小:3.01 MB

页数:9页

时间:2018-09-27

java se 063 反射机制大总结_第1页
java se 063 反射机制大总结_第2页
java se 063 反射机制大总结_第3页
java se 063 反射机制大总结_第4页
java se 063 反射机制大总结_第5页
资源描述:

《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对象的第三种方式ClassclassType=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

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。