美文网首页
注解继承

注解继承

作者: 夜月河色 | 来源:发表于2021-10-09 01:47 被阅读0次

接口注解不能被实现类继承。
接口注解不能被子接口继承。
父类接口能被子类接口继承,注解需要被@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

相关文章

  • 注解继承

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

  • JAVA注解的继承性

    摘要 本文从三个方面介绍java注解的“继承性”: 基于元注解@Inherited,类上注解的继承性 基于类的继承...

  • JAVA注解的使用

    参考文章 注解的定义: 一、定义注解 1.使用@interface2.元注解 注:注解类不支持继承 二、元注解 三...

  • Java注解合并,注解继承

    spring中有时候一个类上面标记很多注解。 实际上Java注解可以进行继承(也就是把多个注解合并成1个) 比如说...

  • 注解

    注解 JDK预定义注解 @Override:检测被该注解标注的方法是否继承自父类(接口)的 @Deprecated...

  • Java自定义注解实战

    注解简介 注解的本质是一个接口,该接口默认继承Annotation接口,使用@interface进行定义。注解主要...

  • spring security 注解@EnableGlobalM

    1、Spring Security默认是禁用注解的,要想开启注解, 需要在继承WebSecurityConfigu...

  • spring security 注解@EnableGlobalM

    1、Spring Security默认是禁用注解的,要想开启注解, 需要在继承WebSecurityConfigu...

  • 通过header控制接口版本

    自定义指定接口版本注解 继承RequestCondition实现自定义 继承 RequestMappingHand...

  • Java注解基础

    注解的本质 注解的本质就是一个继承了Annotation接口的接口 这是注解 @Override 的定义,其实它本...

网友评论

      本文标题:注解继承

      本文链接:https://www.haomeiwen.com/subject/dmifoltx.html