Annotation is not inherited from interface method

前端 未结 3 1715
一个人的身影
一个人的身影 2021-01-17 12:27

I have an interface with an annotated method. The annotation is marked with @Inherited, so I expect an implementor to inherit it. However, it is not the case:

相关标签:
3条回答
  • 2021-01-17 12:33

    From the javadocs of java.lang.annotation.Inherited:

    Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

    0 讨论(0)
  • 2021-01-17 12:33

    From the @Inherited javadoc:

    Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.`

    In summary, it doesn't apply to methods.

    0 讨论(0)
  • 2021-01-17 12:33

    Alternatively, you can use reflection to derive the same information. The method printMethodAnnotations can be rewritten as:

    private static void printMethodAnnotations(Method m) {
        Class<?> methodDeclaredKlass = m.getDeclaringClass();
        List<Class<?>> interfases = org.apache.commons.lang3.ClassUtils.getAllInterfaces(methodDeclaredKlass);
        List<Annotation> annotations = new ArrayList<>();
        annotations.addAll(Arrays.asList(m.getAnnotations()));
        for (Class<?> interfase : interfases) {
            for (Method interfaseMethod : interfase.getMethods()) {
                if (areMethodsEqual(interfaseMethod, m)) {
                    annotations.addAll(Arrays.asList(interfaseMethod.getAnnotations()));
                    continue;
                }
            }
        }
        System.out.println(m + "*: " + annotations);
    }
    
    private static boolean areMethodsEqual(Method m1, Method m2) {
        // return type, Modifiers are not required to check, if they are not appropriate match then it will be a compile
        // time error. This needs enhancements for Generic types parameter ?
        return m1.getName().equals(m2.getName()) && Arrays.equals(m1.getParameterTypes(), m2.getParameterTypes());
    }
    
    0 讨论(0)
提交回复
热议问题