服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 如何获取包下所有类中的注解的值(java工具类)

如何获取包下所有类中的注解的值(java工具类)

2021-11-04 10:49tan_thinker Java教程

这篇文章主要介绍了如何获取包下所有类中的注解的值 (java工具类),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

获取包下所有类中注解的值

作用:

这个工具类主要的作用就是获取类中的注解的值。

应用场景:

做权限的时候获取@RequestMapping();的值,自动添加到数据库中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**   
   * getRequestMappingValue方法描述: 
   * 作者:thh   
   * 日期:2016年7月18日 下午5:41:00        
   * 异常对象:@param packageName
   * 异常对象:@return
*/
    public static List<String> getRequestMappingValue(String packageName) {
    GetAnnotationValueUtil getAnnotationValueUtil = new GetAnnotationValueUtil();
         //第一个class类的集合 
        List<Class<?>> classes = new ArrayList<Class<?>>(); 
        //是否循环迭代 
        boolean recursive = true
        //获取包的名字 并进行替换 
        String packageDirName = packageName.replace('.', '/'); 
        //定义一个枚举的集合 并进行循环来处理这个目录下的文件
        Enumeration<URL> dirs; 
        try
            //读取指定package下的所有class
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()){ 
                URL url = dirs.nextElement(); 
                //得到协议的名称 
                String protocol = url.getProtocol();
                //判断是否以文件的形式保存在服务器上 
                if ("file".equals(protocol)) { 
                    //获取包的物理路径 
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); 
                    //以文件的方式扫描整个包下的文件 并添加到集合中 
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                }
            
        } catch (IOException e) {
            e.printStackTrace(); 
        }
        List<String> stringList = new ArrayList<String>();
        for (Class<?> clazz : classes) {
            //循环获取所有的类
            Class<?> c = clazz;
            //获取类的所有方法
            Method[] methods = c.getMethods();
            for (Method method : methods) {
                //获取RequestMapping注解
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                if (annotation != null) {
                    //获取注解的value值
                    String[] value = annotation.value();
                    for (String string : value) {
                        //放入List集合
                        stringList.add(string);
                    }
                }
            }
        }
        return stringList;
    }
    /**   
     * findAndAddClassesInPackageByFile方法描述: 
     * 作者:thh
     * 日期:2016年7月18日 下午5:41:12        
     * 异常对象:@param packageName
     * 异常对象:@param packagePath
     * 异常对象:@param recursive
     * 异常对象:@param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes){ 
        //获取此包的目录 建立一个File 
        File dir = new File(packagePath); 
        //如果不存在或者 也不是目录就直接返回 
        if (!dir.exists() || !dir.isDirectory()) { 
            return
        
        //如果存在 就获取包下的所有文件 包括目录 
        File[] dirfiles = dir.listFiles(new FileFilter() { 
              //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) 
              public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); 
              
        });
        //循环所有文件 
        for (File file : dirfiles) {
            //如果是目录 则继续扫描 
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), 
                                      file.getAbsolutePath(), 
                                      recursive, 
                                      classes); 
            
            else
                //如果是java类文件 去掉后面的.class 只留下类名 
                String className = file.getName().substring(0, file.getName().length() - 6);
                try
                    //添加到集合中去 
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + "." + className)); 
                } catch (ClassNotFoundException e) { 
                    e.printStackTrace(); 
                
            
        }
    }

java 类,变量,方法上注解值的获取

首先定义三个注解类, 分别适用于类,成员变量, 方法

?
1
2
3
4
5
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LeiMode {
 public int value() default 1;
}
?
1
2
3
4
5
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FiledMode {
 public int value() default 1;
}
?
1
2
3
4
5
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreahMode {
 public int value() default 1;
}

然后,定义一个类,使用了注解

?
1
2
3
4
5
6
7
8
@LeiMode(5)
public class AnnotationDemo {
 @FiledMode(10)
 private int itest;
 
 @TreahMode()
 private void test(){}
}

1.获取类上的注解值

?
1
2
LeiMode annotation = AnnotationDemo.class.getAnnotation(LeiMode.class);
System.out.println(annotation.value());

2.获取所有变量,并获取指定方法上的注解信息

?
1
2
3
4
5
6
7
8
9
10
Field[] fields = AnnotationDemo.class.getDeclaredFields();
  Field field = null;
  for(Field f : fields){
   if(f.getName().equals("itest")){
    field = f;
    break;
   }
  
  FiledMode annotation = field.getAnnotation(FiledMode.class);
  System.out.println(annotation.value());

3.获取指定变量上的注解信息

?
1
2
3
Field field = AnnotationDemo.class.getDeclaredField("itest");
  FiledMode annotation = field.getAnnotation(FiledMode.class); 
  System.out.println(annotation.value());

4.获取所有方法,并获取指定方法上的注解信息

?
1
2
3
4
5
6
7
8
9
10
11
Method[] methods = AnnotationDemo.class.getDeclaredMethods(); //可以获取私有方法和公有方法, getMethods() 获取公有方法
  Method meth = null;
  for(Method method : methods){
   if(method.getName().equals("test")){
    meth = method;
    break;
   }
  }
  Annotation annotation = meth.getAnnotations()[0];
  TreahMode mode = (TreahMode) annotation;
  System.out.println(mode.value());

5.获取指定方法上的注解信息

?
1
2
3
4
5
6
7
8
Method method = AnnotationDemo.class.getDeclaredMethod("test", null);//可以获取私有方法和公有方法
  System.out.println(method);
  Annotation[] annotations = method.getAnnotations();
  Annotation annotation = annotations[0];
  System.out.println(annotation);
  
  TreahMode mode = (TreahMode) annotation;
  System.out.println(mode.value());

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/tan_thinker/article/details/51944593

延伸 · 阅读

精彩推荐