代码之家  ›  专栏  ›  技术社区  ›  Łukasz Bownik

有没有更有效的方法来获取带注释的方法?

  •  11
  • Łukasz Bownik  · 技术社区  · 15 年前

    我开始了一个“为了好玩,没人知道,没人关心”的开源项目( LinkSet

    在一个地方,我需要得到一个类的带注释的方法。

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

    for (final Method method : cls.getDeclaredMethods()) {
    
        final HandlerMethod handler = method.getAnnotation(HandlerMethod.class);
            if (handler != null) {
                    return method;
              }
            }
    
    3 回复  |  直到 15 年前
        1
  •  15
  •   BalusC    10 年前

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

    这里有一个 SSCCE 复制粘贴运行。

    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);
        }
    
    }
    
        2
  •  1
  •   wheaties    15 年前

    回答您的问题:

    Class<?> _class = Whatever.class;
    Annotation[] annos = _class.getAnnotations();
    

    Annotion[] annos = myMethod.getAnnotations();
    

    返回给定方法的所有注释。

        3
  •  1
  •   Bozho    15 年前

    不。但这一点也不低效。

    public static <A extends Annotation> A getAnnotation(
            Method method, Class<A> annotationType) {
    
        return BridgeMethodResolver.
           findBridgedMethod(method).getAnnotation(annotationType);
    }
    

    (如果 BridgedMethodResolver 是另一个主题,但它只返回一个 Method

    而且,与其与 null isAnnotationPresent(YourAnnotation.class) (如问题下面的评论所建议的)