Java seek a method with specific annotation and its annotation element

前端 未结 2 1656
臣服心动
臣服心动 2020-11-30 02:07

Suppose I have this annotation class


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


        
2条回答
  •  孤城傲影
    2020-11-30 03:10

    Here is a method, which returns methods with specific annotations:

    public static List getMethodsAnnotatedWith(final Class type, final Class annotation) {
        final List methods = new ArrayList();
        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
            for (final Method method : klass.getDeclaredMethods()) {
                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;
    }
    

    It can be easily modified to your specific needs. Pls note that the provided method traverses class hierarchy in order to find methods with required annotations.

    Here is a method for your specific needs:

    public static List getMethodsAnnotatedWithMethodXY(final Class type) {
        final List methods = new ArrayList();
        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
            for (final Method method : klass.getDeclaredMethods()) {
                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;
    }
    

    For invocation of the found method(s) pls refer a tutorial. One of the potential difficulties here is the number of method arguments, which could vary between found methods and thus requiring some additional processing.

提交回复
热议问题