1 package com.reflection.test;
2
3 import java.lang.annotation.Annotation;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6
7 import org.springframework.stereotype.Controller;
8 import org.springframework.web.bind.annotation.RequestMapping;
9
10 import com.interview.Controller.ITVCController;
11
12 public class Demo {
13 public static void main(String[] args) throws Exception, InvocationTargetException {
14
15 //通过反射获取类的结构
16 Class<?> itvClass = ITVCController.class;
17
18 //以下是类的注解信息 以及value值
19 System.out.println("以下是类的注解信息 以及value值");
20
21 //获取类的注解信息
22 Annotation[] annotations = itvClass.getAnnotations();
23
24 //遍历注解
25 for (Annotation annotation : annotations) {
26
27 System.out.println(annotation.annotationType().getName());
28
29 //通过反射获取注解的类的结构信息
30 Class<? extends Annotation> annClass = annotation.getClass();
31
32 //获取注解的类的所有方法
33 Method[] methods = annClass.getDeclaredMethods();
34
35 //遍历注解的方法
36 for (Method annMethod : methods) {
37
38 if("value".equals(annMethod.getName())){
39
40 //获取value值
41 Object invoke = annMethod.invoke(annotation);
42
43 Class<? extends Object> class1 = invoke.getClass();
44
45 // 由于我测试的类是SSM的controller层 而controller层的类注解有 @Controller(value="测试")
46 // @RequestMapping(value="calendar")
47 // Controller 的value是String类型 RequestMapping 的value是String[]类型 所以我在猜出进行了一次判断
48
49 if("class java.lang.String".equals(class1.toString())){
50 System.out.println(annMethod.getName()+"====>"+invoke);
51 }else{
52 String[] Strings = (String[])invoke;
53 for (String string : Strings) {
54 System.out.println(annMethod.getName()+"====>"+string);
55 }
56 }
57 }else{
58
59 //输出该注解的方法名
60 System.out.println(annMethod.getName());
61
62 }
63 }
64 }
65
66 //以下是类的方法的注解信息 以及value值
67 System.out.println("以下是类的方法的注解信息 以及value值");
68
69 //获取类的所有方法
70 Method[] methods = itvClass.getDeclaredMethods();
71
72 for (Method method : methods) {
73
74 //以下注释同上
75 Annotation[] metannotation = method.getAnnotations();
76
77 for (Annotation annotation : metannotation) {
78 System.out.println(annotation.annotationType().getName());
79 Class<? extends Annotation> annClass = annotation.getClass();
80 Method[] annMethods = annClass.getDeclaredMethods();
81 for (Method annMethod : annMethods) {
82 if("value".equals(annMethod.getName())){
83 String[] invoke = (String[]) annMethod.invoke(annotation);
84 for (String string : invoke) {
85 System.out.println(annMethod.getName()+"====>"+string);
86 System.out.println();
87 }
88 }
89 }
90 }
91 }
92
93 }
94 }