How to use @inherited annotation in Java?

后端 未结 1 926
独厮守ぢ
独厮守ぢ 2020-12-13 06:06

I am not getting the @Inherited annotation in Java. If it automatically inherits the methods for you then if I need to implement the method in my own way then w

相关标签:
1条回答
  • 2020-12-13 06:10

    Just that there is no misunderstanding: You do ask about java.lang.annotation.Inherited. This is a annotation for annotations.It means that subclasses of annotated classes are considered having the same annotation as their superclass.

    Example

    Consider the following 2 Annotations:

    @Inherited
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface InheritedAnnotationType {
        
    }
    

    and

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface UninheritedAnnotationType {
        
    }
    

    If three classes are annotated like this:

    @UninheritedAnnotationType
    class A {
        
    }
    
    @InheritedAnnotationType
    class B extends A {
        
    }
    
    class C extends B {
        
    }
    

    running this code

    System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));
    System.out.println("_________________________________");
    System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));
    System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class));
    System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));
    

    will print a result similar to this (depending on the packages of the annotation):

    null
    @InheritedAnnotationType()
    @InheritedAnnotationType()
    _________________________________
    @UninheritedAnnotationType()
    null
    null
    

    As you can see UninheritedAnnotationType is not inherited but C inherits annotation InheritedAnnotationType from B.

    I don't know what methods have to do with that.

    0 讨论(0)
提交回复
热议问题