花园小镇

导航

Java反射

 1 package com.reflex;
 2 
 3 import java.lang.reflect.Constructor;
 4 
 5 import java.lang.reflect.Field;
 6 
 7 import java.lang.reflect.InvocationTargetException;
 8 
 9 import java.lang.reflect.Method;
10 
11 import java.util.ArrayList; import java.util.List;
12 
13 import org.junit.Test;
14 
15 //反射定义:反射就是加载类,并解刨类的各个组成部分 public class Demo1 {
16 
17 public static void main(String[] args) throws ClassNotFoundException {
18     // TODO Auto-generated method stub
19     //使用反射,首先要知道有一个Class类代表某一类的字节码
20     //获取某一类字节码的三种办法
21     //1
22     Class clazz = Class.forName("/Test/src/daythree/reflex/Person.java");
23     //2
24     Class clazz1 = new Person().getClass();
25     //3
26     Class clazz2 = Person.class;
27 }
28 @Test //非私有构造函数
29 public void reFlex() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
30     Class clazz = Class.forName("daythree.reflex.Person");
31     Constructor cs = clazz.getConstructor(String.class); //没有参数填写null
32     Person person = (Person) cs.newInstance("12233"); // 实例化        
33 }
34 
35 @Test
36 public void reFlexS() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
37     Class clazz = Class.forName("daythree.reflex.Person");
38     Constructor cs = clazz.getDeclaredConstructor(List.class);
39     cs.setAccessible(true);//暴力反射
40     Person person = (Person) cs.newInstance(new ArrayList<>());========
41     
42 }
43 @Test //方法反射 getMethod 第一个参数方法名 第二个参数方法参数 invoke第一个是方法所在类第二个参数
44 public void FangfaFlex() throws Exception{
45     Person person = new Person();
46     Class clazz = Class.forName("daythree.reflex.Person");
47     Method method = clazz.getMethod("Demo2",null);
48     method.invoke(person, null);        
49 }
50 
51 @Test  //字段发射 从类中赋值 或者取值
52 public void ZiduanFlex() throws Exception{
53     Person person = new Person();
54     Class clazz = Class.forName("daythree.reflex.Person");
55     Field field = clazz.getField("name");
56     //String name = (String)field.get(person); 取值
57     field.set(person, "dashage"); //赋值
58     System.out.println(field.getType()); //取类别
59     System.out.println(person.name);
60 }
61 }
62 
63 class Person {
64 
65 public String name = "shadage";
66 
67 public Person() {
68 
69 }
70 
71 public Person(String a) {
72     System.out.println(a);
73 }
74 
75 private Person(List ls) {
76     System.out.println("true");
77 }
78 
79 public int[] Demo1(int[] a){
80     int b[] = new int[]{1,2,3};
81     return b;
82 }
83 public Class[] Demo1(int a){
84     Class b[] = new Class[]{String.class,int.class};
85     return b;
86 }
87 public void Demo2(){
88     System.out.println("方法输出");
89 }
90 }

 

posted on 2021-04-02 13:12  花园小镇  阅读(54)  评论(0编辑  收藏  举报