有没有办法获取子类方法的参数注解?我尝试使用 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);
}
}
提前致谢!
最佳答案
它不起作用,因为子类 B 中的测试方法与父类(super class)中的测试方法不同。通过重写它,您实际上定义了一种新的测试方法,该方法将代替原始测试方法被调用。如果你像这样定义你的子类
public class B extends A {
}
并再次运行您的代码,它工作正常,因为它是被调用的继承测试方法,据我所知,这就是您想要的。
关于java - 重写方法中的方法参数注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26160297/