Is there any way to get the parameter annotations of a method in child class? I tried using the getParameterAnnotations but it not works. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.