Java寻找具有特定注释及其注释元素的方法

nob*_*ody 37 java reflection annotations

假设我有这个注释类


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodXY {
    public int x();
    public int y();
}

public class AnnotationTest {
    @MethodXY(x=5, y=5)
    public void myMethodA(){ ... }

    @MethodXY(x=3, y=2)
    public void myMethodB(){ ... }
}
Run Code Online (Sandbox Code Playgroud)

那么有没有办法查看一个对象,使用@MethodXY注释"寻找"该方法,其中元素x = 3,y = 2,并调用它?

谢谢

01e*_*1es 63

这是一个方法,它返回带有特定注释的方法:

public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {
    final List<Method> methods = new ArrayList<Method>();
    Class<?> klass = type;
    while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
        // iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
        final List<Method> allMethods = new ArrayList<Method>(Arrays.asList(klass.getDeclaredMethods()));       
        for (final Method method : allMethods) {
            if (method.isAnnotationPresent(annotation)) {
                Annotation annotInstance = method.getAnnotation(annotation);
                // TODO process annotInstance
                methods.add(method);
            }
        }
        // move to the upper class in the hierarchy in search for more methods
        klass = klass.getSuperclass();
    }
    return methods;
}
Run Code Online (Sandbox Code Playgroud)

它可以根据您的特定需求轻松修改.请注意,提供的方法遍历类层次结构,以便查找具有所需注释的方法.

以下是满足您特定需求的方法:

public static List<Method> getMethodsAnnotatedWithMethodXY(final Class<?> type) {
    final List<Method> methods = new ArrayList<Method>();
    Class<?> klass = type;
    while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
        // iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
        final List<Method> allMethods = new ArrayList<Method>(Arrays.asList(klass.getDeclaredMethods()));
        for (final Method method : allMethods) {
            if (method.isAnnotationPresent(MethodXY.class)) {
                MethodXY annotInstance = method.getAnnotation(MethodXY.class);
                if (annotInstance.x() == 3 && annotInstance.y() == 2) {         
                    methods.add(method);
                }
            }
        }
        // move to the upper class in the hierarchy in search for more methods
        klass = klass.getSuperclass();
    }
    return methods;
}
Run Code Online (Sandbox Code Playgroud)

要调用找到的方法,请参阅教程.这里潜在的困难之一是方法参数的数量,这些参数可能在找到的方法之间变化,因此需要一些额外的处理.

  • 我想到目前为止我看到的所有代码示例都涉及"扫描"所有方法 (5认同)