11package com ._520it .reflect2 ;
22
33import java .lang .reflect .Constructor ;
4+ import java .lang .reflect .Field ;
5+ import java .lang .reflect .Method ;
46
57/**
68 * 通过反射获取构造器
@@ -18,9 +20,30 @@ public static void main(String[] args) throws Exception {
1820 //Class clazz3=(new User().getClass());
1921 Constructor [] con =clazz1 .getConstructors ();//将所有的构造器方法放置在通过constructor数组中
2022 System .out .println ("打印数组的长度:" +con .length );
21- /* for(Constructor c1:con){
22- Syste
23+ for (Constructor c1 :con ){
24+ System . out . println ( c1 );
2325 }
24- */ }
26+ Constructor c1 =clazz1 .getDeclaredConstructor ();
27+ User user1 =(User ) c1 .newInstance ();//获取一个实例对象
28+ System .out .println ("-----------------------------" );
29+
30+ Method [] m =clazz1 .getDeclaredMethods ();
31+ for (Method method : m ) {
32+ System .out .println (method );
33+ }
34+ Method m1 =clazz1 .getDeclaredMethod ("method2" ,String .class );
35+ //m1.invoke(user1, "李华");//通过invoke唤醒方法,即调用方法
36+ Field f1 =clazz1 .getDeclaredField ("name" );
37+ f1 .setAccessible (true );
38+ f1 .set (user1 , "王五" );
39+ System .out .println (f1 );
40+ System .out .println ("----------------------------------" );
41+ System .out .println (c1 );
42+ Constructor c2 =clazz1 .getDeclaredConstructor (String .class );
43+ System .out .println (c2 );
44+ Constructor c3 =clazz1 .getDeclaredConstructor (String .class ,int .class );
45+ System .out .println (c3 );
46+
47+ }
2548
2649}
0 commit comments