覆盖方法中的方法参数注释

时间:2014-10-02 11:57:42

标签: java reflection annotations

有没有办法在子类中获取方法的参数注释?我尝试使用getParameterAnnotations,但它不起作用。我写了一个测试类来演示:

public class ParameterAnnotationInheritanceTest {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    @Inherited
    public @interface MockAnnotation {

    }

    public class A {

        public void test(@MockAnnotation String value) {

        }
    }

    public class B extends A {

        @Override
        public void test(String value) {

        }
    }

    @Test
    public void TestA() throws NoSuchMethodException, SecurityException {
        Method AMethod = A.class.getMethod("test", String.class);
        Annotation[][] AMethodParameterAnnotations = AMethod.getParameterAnnotations();
        assertTrue(Arrays.asList(AMethodParameterAnnotations[0]).size() > 0);
    }

    @Test
    public void TestB() throws NoSuchMethodException, SecurityException {
        Method BMethod = B.class.getMethod("test", String.class);
        Annotation[][] BMethodParameterAnnotations = BMethod.getParameterAnnotations();
        assertTrue(Arrays.asList(BMethodParameterAnnotations[0]).size() > 0);
    }

}

提前致谢!

1 个答案:

答案 0 :(得分:1)

它不起作用,因为子类B中的测试方法与超类中的测试方法不同。通过覆盖它,您实际上已经定义了一个被调用而不是原始测试方法的新测试方法。如果您像这样定义您的子类

public class B extends A {

}

并再次运行你的代码,它工作正常,因为它是被调用的继承测试方法,这是你想要的,据我所知。