如何獲取包下所有類中的注解的值(java工具類)
更新時間:2021年08月04日 09:50:39 作者:tan_thinker
這篇文章主要介紹了如何獲取包下所有類中的注解的值 (java工具類),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
獲取包下所有類中注解的值
作用:
這個工具類主要的作用就是獲取類中的注解的值。
應(yīng)用場景:
做權(quán)限的時候獲取@RequestMapping();的值,自動添加到數(shù)據(jù)庫中。
/** * 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<?>>(); //是否循環(huán)迭代 boolean recursive = true; //獲取包的名字 并進(jìn)行替換 String packageDirName = packageName.replace('.', '/'); //定義一個枚舉的集合 并進(jìn)行循環(huán)來處理這個目錄下的文件 Enumeration<URL> dirs; try { //讀取指定package下的所有class dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()){ URL url = dirs.nextElement(); //得到協(xié)議的名稱 String protocol = url.getProtocol(); //判斷是否以文件的形式保存在服務(wù)器上 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) { //循環(huán)獲取所有的類 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() { //自定義過濾規(guī)則 如果可以循環(huán)(包含子目錄) 或則是以.class結(jié)尾的文件(編譯好的java類文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); //循環(huán)所有文件 for (File file : dirfiles) { //如果是目錄 則繼續(xù)掃描 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 類,變量,方法上注解值的獲取
首先定義三個注解類, 分別適用于類,成員變量, 方法
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface LeiMode { public int value() default 1; }
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FiledMode { public int value() default 1; }
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TreahMode { public int value() default 1; }
然后,定義一個類,使用了注解
@LeiMode(5) public class AnnotationDemo { @FiledMode(10) private int itest; @TreahMode() private void test(){} }
1.獲取類上的注解值
LeiMode annotation = AnnotationDemo.class.getAnnotation(LeiMode.class); System.out.println(annotation.value());
2.獲取所有變量,并獲取指定方法上的注解信息
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.獲取指定變量上的注解信息
Field field = AnnotationDemo.class.getDeclaredField("itest"); FiledMode annotation = field.getAnnotation(FiledMode.class); System.out.println(annotation.value());
4.獲取所有方法,并獲取指定方法上的注解信息
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.獲取指定方法上的注解信息
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());
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA創(chuàng)建SpringBoot父子Module項(xiàng)目的實(shí)現(xiàn)
本文主要介紹了IDEA創(chuàng)建SpringBoot父子Module項(xiàng)目的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05IDEA快速部署Spring?Boot?項(xiàng)目到Docker的實(shí)現(xiàn)方法
本文主要介紹了IDEA快速部署Spring?Boot?項(xiàng)目到Docker的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07Java ThreadLocal的設(shè)計(jì)理念與作用
這篇文章主要介紹了Java ThreadLocal的設(shè)計(jì)理念與作用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03SpringBoot自動配置的實(shí)現(xiàn)原理
這篇文章主要介紹了詳解SpringBoot自動配置原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01Java的常見熱門ORM框架優(yōu)缺點(diǎn)區(qū)別
Java?ORM框架是一種用于將Java對象映射到關(guān)系型數(shù)據(jù)庫中的工具,使得開發(fā)人員能夠通過對象操作數(shù)據(jù)庫而不必直接使用SQL查詢,Java開發(fā)變得更加高效和易于維護(hù),選擇適合你的ORM框架是根據(jù)你的需求決定的,比如你的應(yīng)用場景,數(shù)據(jù)結(jié)構(gòu)和技術(shù)水平等2024-02-02