注解继承

接口注解不能被实现类继承。
接口注解不能被子接口继承。
父类接口能被子类接口继承,注解需要被@Inherited元注解注释。

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestAnnotation {
}
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestComponent {
}

public interface UserService extends UserService1 {
    public void get();
}

@TestAnnotation
public interface UserService1 {
}
public class UserServiceChild extends UserServiceImpl{
}
@TestComponent
public class UserServiceImpl implements UserService {
    @Override
    public void get() {
    }
}
class UserServiceImplTest extends BaseJunit {
    @Test
    void testAnnotation() {
        Annotation[] annotations = UserService.class.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("UserService的注解:" + annotations[i]);
        }

        annotations = UserServiceImpl.class.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("UserServiceImpl的注解:" + annotations[i]);
        }

        annotations = UserServiceChild.class.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("UserServiceChild的注解:" + annotations[i]);
        }

        System.out.println(UserService.class.isAnnotationPresent(TestAnnotation.class));
        System.out.println(UserServiceImpl.class.isAnnotationPresent(TestAnnotation.class));
        System.out.println(UserServiceImpl.class.isAnnotationPresent(TestComponent.class));

        System.out.println(UserServiceChild.class.isAnnotationPresent(TestAnnotation.class));
        System.out.println(UserServiceChild.class.isAnnotationPresent(TestComponent.class));
    }
}

结果:

UserServiceImpl的注解:@com.o3gene.listen_jpa.test.TestComponent()
UserServiceChild的注解:@com.o3gene.listen_jpa.test.TestComponent()
false
false
true
false
true

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 引言 父类上的注解能否被子类继承,怎样才能被子类继承?父类方法上的注解呢? 验证 先定义一个注解 然后定义父类,类...
    Thomas_Vader阅读 1,582评论 0 3
  • 同时发布于 知乎 Java 注解 1.注解的由来 在引入注解之前,在不同类型的应用程序使用XML作为标准的代码配置...
    践行者阅读 1,001评论 0 0
  • 元注解 jdk1.5起开始提供了4个元注解,用来定义自定义注解的注解,它们分别是: @Target 指定注解使用的...
    老彭_阅读 607评论 0 0
  • 什么是注解(Annotation):Annotation(注解)就是Java提供了一种元程序中的元素关联任何信息和...
    九尾喵的薛定谔阅读 3,257评论 0 2
  • 注解 创建注解 下面代码创建了一个名为MyAnno的注解,有两个成员str和val。@Retention(…)注解...
    kylinxiang阅读 3,731评论 0 2