【问题标题】:How to scan for annotations in methods only in specific classes using reflection library java?java - 如何使用反射库java仅在特定类中扫描方法中的注释?
【发布时间】:2021-04-25 13:56:44
【问题描述】:

我有一个注释@API,我将它分配给所有路由,即Java spring 中的控制器中的RequestMapping。我想要做的是,首先扫描一个包中用@Controller 注释的所有类,然后扫描所有控制器类,我只想在这些控制器注释类中扫描带有注释@API的方法。

如何在 java 中使用反射来实现这一点?

  Reflections reflections = new Reflections("my.project.prefix");

  Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

【问题讨论】:

  • baeldung.com/reflections-library 将帮助您开始使用 Reflections。返回反射.getTypesAnnotatedWith(FunctionalInterface.class);可能是一个好的开始
  • 您是否正在使用Reflections api,您想在没有它的情况下使用它吗?如果你想没有它,你需要从一个包中获取所有类的部分将是不可能的。
  • 我正在使用反射api
  • 你看过project的READ.ME文件吗?它包含您想知道的所有内容(带注释的类和方法)。
  • 那里看不到任何类似的实现

标签: java spring reflection controller annotations


【解决方案1】:

要使用反射api在包中查找包含@Controller注解的类,可以尝试:

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

要使用反射api在包中查找包含@API注解的方法,可以尝试:

Reflections reflections = new Reflections("my.project.prefix");
Set<Method> methods = reflections
        .getMethodsAnnotatedWith(API.class);

如果您想在仅包含@Controller 注释的类中查找带有@API 注释的方法,您需要编写类似这样的代码:

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<?>> classes = reflections
        .getTypesAnnotatedWith(Controller.class);
for (Class<?> clazz : classes) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof API) {
                // ..
            }
        }
    }
}

【讨论】:

  • 感谢您的出路!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
相关资源
最近更新 更多