5

JAVA中的注解可以继承吗? - JAVA旭阳

 1 year ago
source link: https://www.cnblogs.com/alvinscript/p/16979274.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

注解想必大家都用过,也叫元数据,是一种代码级别的注释,可以对类或者方法等元素做标记说明,比如Spring框架中的@Service@Component等。那么今天我想问大家的是类被继承了,注解能否继承呢?可能会和大家想的不一样,感兴趣的可以往下看。

简单注解继承演示

我们不妨来验证下注解的继承。

  1. 自定义一个注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {

    String value();
}
  • 注解可以被标记在类或者方法上
  1. 使用自定义注解
@TestAnnotation(value = "Class")
static class Parent {

    @TestAnnotation(value = "Method")
    public void method() {

    }
}

static class Child extends Parent {
    
    @Override
    public void method() {
        
    }

}
  • Parent类和里面的方法使用了注解
  • Child类继承了Parent类, 重写了父类的方法
  1. 验证是否存在注解
public static void main(String[] args) throws NoSuchMethodException {

        Parent parent = new Parent();
        log.info("ParentClass: {}", getAnnoValue(parent.getClass().getAnnotation(TestAnnotation.class)));
        log.info("ParentMethod: {}", getAnnoValue(parent.getClass().getMethod("method").getAnnotation(TestAnnotation.class)));

        Child child = new Child();
        log.info("ChildClass: {}", getAnnoValue(child.getClass().getAnnotation(TestAnnotation.class)));
        log.info("ChildMethod: {}", getAnnoValue(child.getClass().getMethod("method").getAnnotation(TestAnnotation.class)));

    }

    private static String getAnnoValue(TestAnnotation annotation) {
        if(annotation == null) {
            return "未找到注解";
        }

        return annotation.value();
    }

输出结果如下:

b813ee620fe144499b68d232201e8584~tplv-k3u1fbpfcp-zoom-1.image

可以看到,父类的类和方法上的注解都可以正确获得,但是子类的类和方法却不能。这说明,默认情况下,子类以及子类的方法,无法自动继承父类和父类方法上的注解。

使用@Inherited演示

查了网上资料以后,在注解上标记@Inherited元注解可以实现注解的继承。那么,把@TestAnnotation注解标记了@Inherited,就可以一键解决问题了吗?

21396317a89b42239f36a0263d5add7f~tplv-k3u1fbpfcp-zoom-1.image

重新运行,得到结果如下:

d0786f5acfc34c63a99db21497194032~tplv-k3u1fbpfcp-zoom-1.image

可以看到,子类可以获得父类类上的注解;子类方法虽然是重写父类方法,并且注解本身也支持继承,但还是无法获得方法上的注解。

如何重写方法继承注解?

实际上,@Inherited只能实现类上的注解继承。要想实现方法上注解的继承,你可以通过反射在继承链上找到方法上的注解。是不是听起来很麻烦,好在Spring框架中提供了AnnotatedElementUtils类,来方便我们处理注解的继承问题。

调用AnnotatedElementUtilsfindMergedAnnotation()方法,可以帮助我们找出父类和接口、父类方法和接口方法上的注解,实现一键找到继承链的注解:

a4d4e4a18cc44a468d3b84941dcdd45c~tplv-k3u1fbpfcp-zoom-1.image

输出结果如下图:

704f040ddcfd49b290940c67e6d3036c~tplv-k3u1fbpfcp-zoom-1.image

自定义注解可以通过标记元注解@Inherited实现注解的继承,不过这只适用于类。如果要继承定义在接口或方法上的注解,可以使用Spring的工具类AnnotatedElementUtils

如果本文对你有帮助的话,请留下一个赞吧
欢迎关注个人公众号——JAVA旭阳
更多学习资料请移步:程序员成神之路


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK