请说明Java注解中@Inherited的作用,并举例说明在反射中如何提取被继承的注解信息。

@Inherited 是 Java 中元注解的一种,用于表示某个注解是否具有继承特性。当一个类被标注了带有 @Inherited 的注解时,该注解的信息可以被子类继承。需要注意的是,@Inherited 仅对类注解有效,而对方法、字段等其他元素的注解无效。

作用

  1. 继承注解:@Inherited 允许子类继承父类上标注的注解。如果子类没有显式标注相同的注解,但父类有标注,则子类可以通过反射获取到继承的注解信息。
  2. 简化代码:通过继承特性,可以减少重复的注解标注,尤其是在需要统一管理的场景中。

示例

定义带有 @Inherited 的注解

import java.lang.annotation.*;

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

标注父类

@MyInheritedAnnotation(value = "ParentClass")
public class ParentClass {}

// 子类未显式标注注解
public class ChildClass extends ParentClass {}

使用反射提取注解信息

import java.lang.annotation.Annotation;

public class Main {
    public static void main(String[] args) {
        // 获取子类的注解信息
        Class<ChildClass> childClass = ChildClass.class;
        Annotation[] annotations = childClass.getAnnotations();
        
        for (Annotation annotation : annotations) {
            if (annotation instanceof MyInheritedAnnotation) {
                MyInheritedAnnotation inheritedAnnotation = (MyInheritedAnnotation) annotation;
                System.out.println("继承的注解值: " + inheritedAnnotation.value());
            }
        }
    }
}

输出结果

运行上述代码后,输出结果为:

继承的注解值: ParentClass

详细说明

  1. 注解定义:@Inherited 需要在定义注解时显式标注,否则注解不具备继承特性。
  2. 反射提取:通过 Class.getAnnotations() 方法可以获取类上所有的注解(包括继承的注解)。在反射中,getAnnotations() 方法会返回继承链上的所有注解,而 getDeclaredAnnotations() 仅返回当前类显式标注的注解。

注意事项

  • 局限性:@Inherited 仅适用于类级别的注解,对方法、字段等无效。
  • 间接继承:如果子类覆盖了父类的方法或字段,该特性不会传递到子类中。
  • 接口无效:注解不会通过接口继承传递。

通过以上示例和说明,可以清晰了解 @Inherited 的作用及其在反射中的具体应用场景。