如何獲取包下所有類中的注解的值(java工具類)
更新時(shí)間:2021年08月04日 09:50:39 作者:tan_thinker
這篇文章主要介紹了如何獲取包下所有類中的注解的值 (java工具類),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
獲取包下所有類中注解的值
作用:
這個(gè)工具類主要的作用就是獲取類中的注解的值。
應(yīng)用場(chǎng)景:
做權(quán)限的時(shí)候獲取@RequestMapping();的值,自動(dòng)添加到數(shù)據(jù)庫(kù)中。
/**
* getRequestMappingValue方法描述:
* 作者:thh
* 日期:2016年7月18日 下午5:41:00
* 異常對(duì)象:@param packageName
* 異常對(duì)象:@return
*/
public static List<String> getRequestMappingValue(String packageName) {
GetAnnotationValueUtil getAnnotationValueUtil = new GetAnnotationValueUtil();
//第一個(gè)class類的集合
List<Class<?>> classes = new ArrayList<Class<?>>();
//是否循環(huán)迭代
boolean recursive = true;
//獲取包的名字 并進(jìn)行替換
String packageDirName = packageName.replace('.', '/');
//定義一個(gè)枚舉的集合 并進(jìn)行循環(huán)來(lái)處理這個(gè)目錄下的文件
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");
//以文件的方式掃描整個(gè)包下的文件 并添加到集合中
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
* 異常對(duì)象:@param packageName
* 異常對(duì)象:@param packagePath
* 異常對(duì)象:@param recursive
* 異常對(duì)象:@param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes){
//獲取此包的目錄 建立一個(gè)File
File dir = new File(packagePath);
//如果不存在或者 也不是目錄就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
//如果存在 就獲取包下的所有文件 包括目錄
File[] dirfiles = dir.listFiles(new FileFilter() {
//自定義過(guò)濾規(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 類,變量,方法上注解值的獲取
首先定義三個(gè)注解類, 分別適用于類,成員變量, 方法
@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;
}
然后,定義一個(gè)類,使用了注解
@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());
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
RabbitMQ中的prefetch_count參數(shù)詳解
這篇文章主要介紹了RabbitMQ中的prefetch_count參數(shù)用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
java計(jì)算值所占的百分比,結(jié)果為100%問(wèn)題
這篇文章主要介紹了java計(jì)算值所占的百分比,結(jié)果為100%問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
解析Java的設(shè)計(jì)模式編程之解釋器模式的運(yùn)用
這篇文章主要介紹了解析Java的設(shè)計(jì)模式編程之解釋器模式的運(yùn)用,文中對(duì)解釋器模式的優(yōu)缺點(diǎn)及適用場(chǎng)景作出了分析,需要的朋友可以參考下2016-02-02
Junit 5中@ParameterizedTest與@EnumSource結(jié)合使用
今天小編就為大家分享一篇關(guān)于Junit 5中@ParameterizedTest與@EnumSource結(jié)合使用,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
關(guān)于.java編譯成.class?與?.class反編譯成.java問(wèn)題
這篇文章主要介紹了關(guān)于.java編譯成.class?與?.class反編譯成.java問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09

