1 package com.yubaby.annotation.p2;
2
3 /*
4 * 在程序使用(解析)注解:获取注解中定义的属性值
5 1. 获取注解定义的位置的对象 (Class,Method,Field)
6 2. 获取指定的注解
7 * getAnnotation(Class)
8 //其实就是在内存中生成了一个该注解接口的子类实现对象
9
10 public class ProImpl implements Pro{
11 public String className(){
12 return "cn.itcast.annotation.Demo1";
13 }
14 public String methodName(){
15 return "show";
16 }
17 }
18 3. 调用注解中的抽象方法获取配置的属性值
19
20 利用注解重构"JavaWeb-1.2.3【基础加强:案例(反射+配置文件)】"
21 对此案例,相较于利用配置文件,利用注解实现可以简化
22 */
23
24 import java.lang.reflect.Method;
25
26 /**
27 * 框架类
28 */
29
30 @Pro(className = "com.yubaby.annotation.p2.Dog", methodName = "eat")
31 public class ReflectTest {
32 public static void main(String[] args) throws Exception{
33 //解析注解
34
35 //1 获取本类的字节码文件对象
36 Class<ReflectTest> reflectTestClass = ReflectTest.class;
37
38 //2 获取注解对象
39 Pro annotation = reflectTestClass.getAnnotation(Pro.class);
40 /*
41 其实就是在内存中生成了一个该注解接口的子类实现对象
42 public class ProImpl implements Pro{
43 public String className(){
44 return "com.yubaby.annotation.p2.Dog";
45 }
46 public String methodName(){
47 return "eat";
48 }
49
50 }
51 */
52
53 //3 调用注解对象中定义的抽象方法(又称属性),获取返回值
54 String className = annotation.className();
55 String methodName = annotation.methodName();
56 // System.out.println(className); //com.yubaby.annotation.p2.Dog
57 // System.out.println(methodName); //eat
58
59 //4.加载该类进内存
60 Class cls = Class.forName(className);
61
62 //5.创建对象
63 Object obj = cls.getDeclaredConstructor().newInstance(); //类对象
64 Method method = cls.getMethod(methodName); //方法对象
65
66 //6.执行方法
67 method.invoke(obj); //狗吃狗粮
68 }
69 }
1 package com.yubaby.annotation.p2;
2
3 import java.lang.annotation.ElementType;
4 import java.lang.annotation.Retention;
5 import java.lang.annotation.RetentionPolicy;
6 import java.lang.annotation.Target;
7
8 /**
9 * 代替配置文件pro.properties
10 * 描述需要执行的类名和方法名
11 */
12
13 @Target({ElementType.TYPE}) //希望作用与类上
14 @Retention(RetentionPolicy.RUNTIME) //希望被保留在RUNTIME阶段
15 public @interface Pro {
16 String className();
17 String methodName();
18 }
1 package com.yubaby.annotation.p2;
2
3 public class Cat {
4 public void eat(){
5 System.out.println("猫吃猫粮");
6 }
7 }
1 package com.yubaby.annotation.p2;
2
3 public class Dog {
4 public void eat(){
5 System.out.println("狗吃狗粮");
6 }
7 }