Java注解的继承

时间:2025-04-23 11:50:17
  • 类、方法、参数上的注解都可以被继承
  • 如果方法被重写了,方法上和参数上的 Annotation 将不会被继承,但是类的注解还是会被继承
  • Annotation 的继承不能应用在接口上
  • 类、方法、参数上的注解都可以被继承
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedTest {
    String hello();
}

@InheritedTest(hello = "bob")
public class InheritedParent {

    @InheritedTest(hello = "smith")
    public void doSomething(@InheritedTest(hello = "param") String param){
        System.out.println("Parent do something!");
    }
}

public class InheritedChild extends InheritedParent {


}

测试

//类注解的继承
@Test
public void test01(){
    Class<InheritedChild> inheritedChildClass = InheritedChild.class;
    if(inheritedChildClass.isAnnotationPresent(InheritedTest.class)){
        InheritedTest annotation = inheritedChildClass.getAnnotation(InheritedTest.class);
        System.out.println(annotation.hello());
    }
}

//方法注解的继承
@Test
public void test02() throws NoSuchMethodException {
    Class<InheritedChild> inheritedChildClass = InheritedChild.class;
    Method doSomething = inheritedChildClass.getMethod("doSomething", new Class[]{});
    if (doSomething.isAnnotationPresent(InheritedTest.class)) {
        InheritedTest annotation = doSomething.getAnnotation(InheritedTest.class);
        System.out.println(annotation.hello());
    }
}

//参数注解的继承
@Test
public void test03() throws NoSuchMethodException {
    Class<InheritedChild> inheritedTestClass = InheritedChild.class;
    Method doSomething = inheritedTestClass.getMethod("doSomething", new Class[]{String.class});
    Parameter[] parameters = doSomething.getParameters();
    for (Parameter parameter : parameters) {
        if (parameter.isAnnotationPresent(InheritedTest.class)) {
            InheritedTest annotation = parameter.getAnnotation(InheritedTest.class);
            System.out.println(annotation.hello());
        }
    }
}

如果方法被重写了,方法上和参数上的 Annotation 将不会被继承,但是类的注解还是会被继承

public class InheritedChild extends InheritedParent {

    public void doSomething(String param){
        System.out.println("Parent do something!");
    }

}

测试

//方法注解的继承
@Test
public void test02() throws NoSuchMethodException {
    Class<InheritedChild> inheritedChildClass = ;
    Method doSomething = ("doSomething", new Class[]{});
    if (()) {
        InheritedTest annotation = ();
        (());
    }
}

Annotation 的继承不能应用在接口上

@InheritedTest(hello = "interface")
public interface InheritedParent02 {
}

public class InheritedChild02 implements InheritedParent02{
}

//接口注解的继承
@Test
public void test04(){
    Class<InheritedChild02> inheritedChild02Class = InheritedChild02.class;
    if (inheritedChild02Class.isAnnotationPresent(InheritedTest.class)) {
        InheritedTest annotation = inheritedChild02Class.getAnnotation(InheritedTest.class);
        System.out.println(annotation.hello());
    }
}

参考:/blog/yahaitt-144565