1.调用运行时类的属性
1 public static void testField() throws Exception {
2 Class clazz = Person.class;
3 //创建运行时类的对象
4 Person p = (Person) clazz.newInstance();
5 //获取指定的公有(public)属性(使用情况少)
6 Field id = clazz.getField("id");
7 /*
8 设置当前的属性值
9 set(参数1,参数2):参数1:指明设置哪个参数对象的属性,参数2:将此属性设置为多少
10 get(参数1):
11 */
12 id.set(p,101);
13 int pId = (int) id.get(p);
14 System.out.println(pId + "——" + id);
15 }
1 public static void testField1() throws Exception {
2 Class clazz = Person.class;
3 Person p = (Person) clazz.newInstance();
4 Field name = clazz.getDeclaredField("name");
5 name.setAccessible(true);
6 name.set(p,"tom");
7 System.out.println(name.get(p));
8 }
2.调用运行时类的方法
1 public static void testMethod() throws Exception {
2 Class clazz = Person.class;
3 Person p = (Person) clazz.newInstance();
4 /*
5 获取类的指定方法:
6 getDeclaredMethod():参数1:方法名 参数2:指明获取方法的参数列表
7 */
8 Method show = clazz.getDeclaredMethod("show",String.class);
9 //保证当前方法可访问
10 show.setAccessible(true);
11 /*
12 调用方法的invoke():参数1即为方法的调用者 参数2:给方法形参赋值的实参
13 invoke()的返回值即为对应类中调用的返回值
14 */
15 Object returnValue = show.invoke(p, "CHN");//p.show("CHN");
16 System.out.println(returnValue);
17
18 //调用静态方法
19 Method desc = clazz.getDeclaredMethod("desc");
20 desc.setAccessible(true);
21 //如果无返回值则得到null
22 Object invoke = desc.invoke(Person.class);
23 System.out.println(invoke);
24 }
3.调用运行时类的构造器
1 public static void testConstructor() throws Exception {
2 Class clazz = Person.class;
3 /*
4 获取指定的构造器
5 getDeclaredConstructor():参数,指明构造器的参数列表
6 */
7 Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
8 //保证构造器是可访问的
9 declaredConstructor.setAccessible(true);
10 //调用此构造器创建运行时类的对象
11 Person per = (Person) declaredConstructor.newInstance();
12 System.out.println(per);
13
14 }
原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/273618.html