欢迎来到天天文库
浏览记录
ID:39549658
大小:71.67 KB
页数:21页
时间:2019-07-06
《java反射详解》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、java反射详解本篇文章依旧采用小例子来说明,因为我始终觉的,案例驱动是最好的,要不然只看理论的话,看了也不懂,不过建议大家在看完文章之后,在回过头去看看理论,会有更好的理解。下面开始正文。【案例1】通过一个对象获得完整的包名和类名?123456789101112131415packageReflect; /** *通过一个对象获得完整的包名和类名 **/classDemo{ //othercodes...} classhello{ publicstaticvoidmain(String[]args){
2、 Demodemo=newDemo(); System.out.println(demo.getClass().getName()); }}【运行结果】:Reflect.Demo添加一句:所有类的对象其实都是Class的实例。【案例2】实例化Class类对象?12345678910111213141516packageReflect;classDemo{ //othercodes...} classhello{ publicstaticvoidmain(String[]a
3、rgs){ Class>demo1=null; Class>demo2=null; Class>demo3=null; try{ //一般尽量采用这种形式 demo1=Class.forName("Reflect.Demo"); }catch(Exceptione){ e.printStackTrace(); }171819202122232425
4、 demo2=newDemo().getClass(); demo3=Demo.class; System.out.println("类名称 "+demo1.getName()); System.out.println("类名称 "+demo2.getName()); System.out.println("类名称 "+demo3.getName()); }}【运行结果】:类名称 Reflect.Demo类名
5、称 Reflect.Demo类名称 Reflect.Demo【案例3】通过Class实例化其他类的对象通过无参构造实例化对象?1234567891011121314151617181920212223packageReflect; classPerson{ publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicint
6、getAge(){ returnage; } publicvoidsetAge(intage){ this.age=age; } @Override publicStringtoString(){ return"["+this.name+" "+this.age+"]"; } privateStringname; privateintage;}24252627282930313233343536373839404142434445
7、4647 classhello{ publicstaticvoidmain(String[]args){ Class>demo=null; try{ demo=Class.forName("Reflect.Person"); }catch(Exceptione){ e.printStackTrace(); } Personper=null; try{ per=
8、(Person)demo.newInstance(); }catch(InstantiationExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }catch(IllegalAcc
此文档下载收益归作者所有