晟天帝成神之路
中二病洛晟危
 1 package cn.itsource._05test;
 2 
 3 import java.lang.reflect.Field;
 4 
 5 //测试类:
 6 //    关于注解与反射综合的示例
 7 public class Test {
 8 
 9     public static void main(String[] args) throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
10         Injection ij = new Injection();
11         
12         //执行了第三方程序,通过注解标记,决定是否注入对象
13         
14         threeCode(ij);
15         ij.pson.println();//会报错,空指针异常,因为pson没有对象,null
16         
17 
18     }
19 
20     public static void threeCode(Object obj) throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException{
21         //拿到了Injection的字节码文件
22         Class cla = obj.getClass();
23         //通过Injection的字节码文件拿到里面的pson字段
24         Field pson = cla.getField("pson");
25         //拿到pson字段的类型,拿到字节码文件
26         Class typeperson = pson.getType();
27         //判断字段pson,是否有注解AutoWired
28         AutoWired annotation = pson.getAnnotation(AutoWired.class);
29         //拿到注解类型对象annotation,通过annotation获得注解的值
30         System.out.println(annotation.value());//取注解的值
31         if(annotation == null){
32             return;
33         }
34         //根据typePerson,创建要给Person对象
35         Object person = typeperson.newInstance();
36         
37         //把创建的Person对象,放入字段pson
38         pson.set(obj, person);
39     }
40     
41 
42 }

 

posted on 2022-11-30 21:10  洛晟  阅读(21)  评论(0)    收藏  举报