Java扫描指定包下所有添加了自定义注解的方法信息

该文章介绍了一个使用Java和Spring框架的方法,通过AnnotationUtil工具类来扫描并获取指定包下所有包含特定自定义注解的方法信息。AnnotationUtil类利用ResourceLoader和MetadataReaderFactory进行资源和元数据读取,遍历类路径下资源,解析出带有注解的方法及其属性值。
摘要由CSDN通过智能技术生成

自定义注解

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Req {
	String desc() default "";
}

扫描并输出所有包含上面自定义注解的方法

@Componet
public class AnnotationUtil{
	@Resource
	private ResourceLoader resourceLoader;
	/**
	 * 获取指定包下所有添加了自定义注解的方法信息
	 * @param classPath 包名
	 * @param annotation 注解类名
	 * @return Map<方法名,map<注解属性,值>>
	 * /
	public <T> Map<>String, Map<String, Object>> getAllAnnotatedMethods(String classPath, Classs<T> annotation){
	Map<String, Map<String, Object>> map = new HashMap<>();
	ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
	MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
	Resource[] resources = resolver.getResources(classPath);
	for(org.springframework.core.io.Resource r: resources){
		MetadataReader reader = metaReader.getMetadataReader(r);
		//逐个解析
		map = resolveClass(reader, map, annotation);
	}
	return map;
}

private <T> Map<String, Map<String, Object>> resolveClass(MetadataReader reader, Map<String, Map<String, Object>> map, Class<T> annotation){
	String annotationCanonicalName = annotation.getCanonicalName();
	//获取注解元数据
	AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
	//获取类名
	String fullClassName = annotationMetadata.getClassName();
	String className = StringUtils.substring(fullClassName, fullClassName.lastIndexOf(".") + 1, fullClassName.length());
	//获取当前类中添加自定义注解的方法
	Set<MethodMetadata> annotatedMethods = annotationMetadata.getAnnotatedMethods(annotationCanonicalName);
	for(MethodMetadata annotatedMethod: annotatedMethods){
		//获取方法名	
		String methodName = annotatedMethod.getMethodName();
		//获取当前方法中要扫描注解的属性
		Map<String, Object> targetAttr = annotatedMethod.getAnnotaionAttributes(annotationCanonicalName);
		map.put(className + "-" + methodName, targetAttr);
	}
	return map;
}

调用AnnotationUtil

String classpath = "classpath*:com/czg/**/*.class";
Map<String, Map<String, Object>> annotatedMethods = annotationUtil.getAllAnnotatedMathods(classpath, Req.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W如Q扬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值