How do Java method annotations work in conjunction with method overriding?

后端 未结 4 1386
清酒与你
清酒与你 2020-11-28 06:39

I have a parent class Parent and a child class Child, defined thus:

class Parent {
    @MyAnnotation("hello")
    void foo         


        
4条回答
  •  时光取名叫无心
    2020-11-28 06:50

    You found your answer already: there is no provision for method-annotation inheritance in the JDK.

    But climbing the super-class chain in search of annotated methods is also easy to implement:

    /**
     * Climbs the super-class chain to find the first method with the given signature which is
     * annotated with the given annotation.
     *
     * @return A method of the requested signature, applicable to all instances of the given
     *         class, and annotated with the required annotation
     * @throws NoSuchMethodException If no method was found that matches this description
     */
    public Method getAnnotatedMethod(Class annotation,
                                     Class c, String methodName, Class... parameterTypes)
            throws NoSuchMethodException {
    
        Method method = c.getMethod(methodName, parameterTypes);
        if (method.isAnnotationPresent(annotation)) {
            return method;
        }
    
        return getAnnotatedMethod(annotation, c.getSuperclass(), methodName, parameterTypes);
    }
    

提交回复
热议问题