@Inherited
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。
1、如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
2、@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,
3、方法并不从它所重载的方法继承annotation。
错误理解:
1、接口中加上某个注解,实现接口的类都可以获取到接口上面的注解
2、父类中的方法中有的注解,子类重新了父类的方法,可以获取到这个注解
这两点理解是错误的。
上代码:
package com.ms.anno.inherited;
import java.lang.annotation.*;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:18 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Annotation1 {
}
package com.ms.anno.inherited;
import java.lang.annotation.*;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:18 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Annotation2 {
}
package com.ms.anno.inherited;
import java.lang.annotation.*;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:18 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Annotation3 {
}
package com.ms.anno.inherited;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:18 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
@Annotation1
public interface IService {
}
package com.ms.anno.inherited;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:22 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
@Annotation2
public class AService {
@Annotation3
void m1(){}
}
package com.ms.anno.inherited;
import com.ms.aop.execution.IServiceA;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:19 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
public class ServiceImpl extends AService implements IService {
@Override
void m1() {
super.m1();
}
}
package com.ms.anno.inherited;
import java.lang.annotation.Annotation;
import java.util.Arrays;
/**
* <b>description</b>: <br>
* <b>time</b>:2019/4/28 10:20 <br>
* <b>author</b>:十年java老兵,只生产干货,公众号:路人甲Java,微信号:itsoku
*/
public class Client {
public static void main(String[] args) {
Annotation[] annotations = ServiceImpl.class.getAnnotations();
System.out.println("ServiceImpl 注解列表:");
Arrays.stream(annotations).forEach(System.out::println);
}
}
运行结果:
ServiceImpl 注解列表:
@com.ms.anno.inherited.Annotation2()
总结
1、@Inherited只有用在class上,注解才可以被子类获取到,用在接口、方法上,不会被子类获取到