如何扫描类注释?

loy*_*low 15 java servlets guice guava

我有一个简单的jane servlets Web应用程序,我的一些类有以下注释:

@Controller
@RequestMapping(name = "/blog/")
public class TestController {
..

}
Run Code Online (Sandbox Code Playgroud)

现在,当我的servlet应用程序启动时,我想获得所有具有@Controller注释的类的列表,然后获取@RequestMapping注释的值并将其插入字典中.

我怎样才能做到这一点?

我也使用Guice和Guava,但不确定是否有任何与注释相关的助手.

Jac*_*oen 36

您可以使用Reflections库,为其提供您要查找的包和注释.

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Controller.class);

for (Class<?> controller : annotated) {
    RequestMapping request = controller.getAnnotation(RequestMapping.class);
    String mapping = request.name();
}
Run Code Online (Sandbox Code Playgroud)

当然,将所有servlet放在同一个包中会使这更容易一些.此外,您可能希望查找具有RequestMapping注释的类,因为这是您要从中获取值的类.


chk*_*kal 5

扫描注释非常困难。您实际上必须处理所有类路径位置并尝试查找对应于 Java 类 (*.class) 的文件。

我强烈建议使用提供此类功能的框架。例如,您可以查看Scannotation

  • 非常困难???我会说它 [非常简单](http://unixhelp.ed.ac.uk/CGI/man-cgi?find) 当你知道你的 CLASSPATH(你通常做什么)。但我同意使用一个好的工具是一个好主意。 (2认同)
  • 如果你想有效地做到这一点,这是非常困难的。特别是如果您不想为类路径上的所有类创建类实例。 (2认同)

swa*_*ina 5

如果您使用的是 Spring,

它有一个叫做AnnotatedTypeScanner类的东西。
这个类内部使用

ClassPathScanningCandidateComponentProvider
Run Code Online (Sandbox Code Playgroud)

此类具有用于实际扫描类路径资源的代码。它通过使用运行时可用的类元数据来做到这一点。

可以简单地扩展这个类或使用相同的类进行扫描。下面是构造函数定义。

   /**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     * 
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }
Run Code Online (Sandbox Code Playgroud)