在运行时扫描 Java 注释 [英] Scanning Java annotations at runtime

查看:38
本文介绍了在运行时扫描 Java 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在整个类路径中搜索带注释的类?

How do I search the whole classpath for an annotated class?

我正在做一个库,我想允许用户注释他们的类,所以当 Web 应用程序启动时,我需要扫描整个类路径以获取某些注释.

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

我正在考虑 Java EE 5 Web 服务或 EJB 的新功能.您使用 @WebService@EJB 注释您的类,系统会在加载时找到这些类,以便远程访问它们.

I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system finds these classes while loading so they are accessible remotely.

推荐答案

使用 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API

从基本包扫描类路径的组件提供程序.然后将排除和包含过滤器应用于结果类以查找候选者.

A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
    System.out.println(bd.getBeanClassName());

这篇关于在运行时扫描 Java 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆