是否有更有效的方法来获得带注释的方法?

Łuk*_*nik 11 java reflection

我开始了"为了好玩,没有人知道,没人关心"开源项目(LinkSet).

在一个地方,我需要获得一个类的注释方法.

有没有比这更有效的方法呢?我的意思是不需要遍历每个方法?

for (final Method method : cls.getDeclaredMethods()) {

    final HandlerMethod handler = method.getAnnotation(HandlerMethod.class);
        if (handler != null) {
                return method;
          }
        }
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 12

看一下Reflections(依赖项:GuavaJavassist).这是一个已经优化了大部分内容的库.有一个Reflections#getMethodsAnnotatedWith()适合您的功能需求.

这是一个SSCCE,只是复制'n'paste'n'run它.

package com.stackoverflow;

import java.lang.reflect.Method;
import java.util.Set;

import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

public class Test {

    @Deprecated
    public static void main(String[] args) {
        Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("com.stackoverflow"))
            .setScanners(new MethodAnnotationsScanner()));
        Set<Method> methods = reflections.getMethodsAnnotatedWith(Deprecated.class);
        System.out.println(methods);
    }

}
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 1

不。但这一点也不低效。

例如 spring 使用以下代码:

public static <A extends Annotation> A getAnnotation(
        Method method, Class<A> annotationType) {

    return BridgeMethodResolver.
       findBridgedMethod(method).getAnnotation(annotationType);
}
Run Code Online (Sandbox Code Playgroud)

(其中BridgedMethodResolver是另一个主题,但它只返回一个Method对象)

另外,null您可以检查是否存在注释,而不是与 进行比较isAnnotationPresent(YourAnnotation.class)(如问题下面的评论中所建议的)