@Inherited注解

发布时间 2023-09-07 19:22:59作者: 想去大上海

在Java中,@Inherited是一个注解(annotation),用于指示一个类的继承行为。当一个类被标记为@Inherited时,它的子类将继承父类的注解。

具体来说,当一个类被标记为@Inherited时,它的所有方法、字段和构造函数都将被子类继承。这意味着,如果子类没有显式地声明与父类相同的方法、字段或构造函数,那么这些方法、字段或构造函数将自动从父类继承过来。

需要注意的是,@Inherited注解只适用于注解本身,而不适用于注解的内容。如果一个注解的内容是一个类或方法,那么该注解本身并不能被子类继承。

以下是一个示例代码,演示了如何使用@Inherited注解:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface MyAnnotation {
String value();
}

@MyAnnotation(value = "hello")
public class Parent {
public void parentMethod() {
System.out.println("This is a method from parent class.");
}
}

public class Child extends Parent {
public void childMethod() {
System.out.println("This is a method from child class.");
}
}

public class Main {
public static void main(String[] args) {
Child child = new Child();
child.parentMethod(); // 输出:This is a method from parent class.
child.childMethod(); // 输出:This is a method from child class.

// 使用反射获取Child类的注解信息,并打印出来
MyAnnotation childAnnotation = child.getClass().getAnnotation(MyAnnotation.class);
System.out.println(childAnnotation.value()); // 输出:hello
}
}

在上述代码中,我们定义了一个名为MyAnnotation的注解,并将其标记为@Inherited。然后,我们定义了一个父类Parent,并使用@MyAnnotation注解标记它。接着,我们定义了一个子类Child,并扩展了父类。在子类中,我们定义了一个自己的方法childMethod()。最后,我们在主函数中创建了一个子类对象,并分别调用了父类和子类的方法。此外,我们还使用反射获取了子类的注解信息,并打印出来。

需要注意的是,在Java中,默认情况下一个类的继承关系是不被继承的。因此,如果一个子类没有显式地声明与父类相同的方法、字段或构造函数,那么这些方法、字段或构造函数将不会自动从父类继承过来。如果需要改变这种默认行为,可以使用@Inherited注解来实现。