Inherited元注解使用

123 阅读2分钟

@Inherited元注解使用

❓我们都知道java的三大特性:封装、继承、多态。本次主要谈谈跟继承有关系的内容,继承父类,可以在子类中调用父类的一些方法,那么在使用自定义注解的时候是否也可以继承在父类上使用的注解内容呢?

接下来我们来上手实战,自定义一个注解。

自定义注解(Value)

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
​
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Value {
​
    String value();
}

Parent类

@Value(value = "parent")
public class Parent {
}

Child类

public class Child extends Parent {
}

测试类

import java.lang.annotation.Annotation;
​
public class AnnoMain {
​
    public static void main(String[] args) {
        Annotation[] annotations = Child.class.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.annotationType() + " " + annotation);
        }
    }
}
没有使用Inherited情况下输出
  • 执行结果:

image.png

使用Inherited情况下输出
  • 调整下Value注解
import java.lang.annotation.*;
​
@Inherited // 添加Inherited
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Value {
​
    String value();
}
  • 执行结果:

image.png

那么如果我在子类上添加一个Value注解,输出的内容又会是什么样子呢?

  • 调整Child类,添加注解Value
  @Value(value = "child")
  public class Child extends Parent {
  }
  • 执行结果:

image.png

我们会发现,此处输出的结果是child,在子类与父类同时添加自定义注解时,子类会覆盖掉父类的注解内容。

💡这时我就有个新的疑问了,既然继承可以如此使用注解,那么如果是接口类的实现呢?话不多说,直接开写代码。

编写IParent接口类和ChildImpl实现类

IParent接口类

@Value(value = "iparent")
public interface IParent {
}

ChildImpl实现类

public class ChildImpl implements IParent {
}

测试类

import java.lang.annotation.Annotation;
​
public class AnnoInterfaceMain {
​
    public static void main(String[] args) {
        Annotation[] annotations = ChildImpl.class.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.annotationType() + " " + annotation);
        }
    }
}

执行结果:

image.png

可以看出,输出的内容为空,接口类添加注解无法输出注解内容。

那么我们再做一次调整,在实现类上添加注解Value

调整ChildImpl实现类

@Value(value = "ichild")
public class ChildImpl implements IParent {
}

执行结果:

image.png

❗️通过实现可以看出接口上注解是无法解析出结果的,只有类上可以解析成功,换而言之就是说只能继承 class 上的注解,其它都无法继承。