简体   繁体   English

重写方法中的方法参数注释

[英]Method Parameter Annotations in overridden methods

Is there any way to get the parameter annotations of a method in child class? 有什么方法可以在子类中获取方法的参数注释吗? I tried using the getParameterAnnotations but it not works. 我尝试使用getParameterAnnotations,但它不起作用。 I wrote a test class to demonstrate: 我编写了一个测试类来演示:

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);
    }

}

Thanks in advance! 提前致谢!

It does not work because the test method in the child class B is not the same test method as in the super class. 它不起作用,因为子类B中的测试方法与父类中的测试方法不同。 By overriding it, you have practically defined a new test method that gets called instead of the original one. 通过覆盖它,您实际上定义了一种新的测试方法,该方法被调用而不是原始方法。 If you define your child class like this 如果您这样定义孩子班级

public class B extends A {

}

and run your code again, it works fine because it is the inherited test method that gets called, which is what you want as far as I understand. 并再次运行您的代码,它可以正常工作,因为据我所知,这是被调用的继承测试方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM