如何扫描类注释? [英] How to scan classes for annotations?

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

问题描述

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

I have a plain jane servlets web application, and some of my classes have the following annotations:

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

}

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

Now when my servlet applications starts up, I would like to get a list of all classes that have the @Controller annotation, and then get the value of the @RequestMapping annotation and insert it in a dictionary.

我该怎么做?

我正在使用Guice和Guava另外,但不确定是否有任何与注释相关的助手。

I'm using Guice and Guava also, but not sure if that has any annotation related helpers.

推荐答案

您可以使用思考库,为它提供您要查找的包和注释。

You can use the Reflections library by giving it the package and Annotation you are looking for.

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();
}

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

Of course placing all your servlets in the same package makes this a little easier. Also you might want to look for the classes that have the RequestMapping annotation instead, since that is the one you are looking to get a value from.

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

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