Java自带的注解
@Deprecated 表明当前的元素已经不推荐使用@Override 表明当前方法是覆盖了父类方法@SuppressWarnings 关闭不当的编译器警告信息
自定义注解
@
interface Empty{
String field1()
default "it's empty";
}
@
Empty
class C{
}
@
Empty(field1=
"empty A")
class A{
}
@
interface Value{
String value();
String other()
default "it's great";
}
@Value(
"empty B")
class B{
}
元注解
@Documented
被修饰的注解会生成到javadoc中
@Documented
@interface DocumentedAnnotation{
}
@interface UnDocumentedAnnotation{
}
@DocumentedAnnotation
@UnDocumentedAnnotation
class A{}
@Retention
可以设置注解的级别
@Retention(RetentionPolicy.CLASS)
@interface ClassRetentionAnnotation{}
SOURCE代表源码级别,注解只存在源码中,其功能是与编译器交互,用于代码检测,如@Override,@SuppressWarings,许多框架如Dragger就是使用这个级别的注解,这个级别的框架额外效率损耗发生在编译时
CLASS代表字节码级别,注解存在源码与字节码文件中,主要用于编译时生成而外的文件,如XML,Java文件等,这个级别需要添加JVM加载时候的代理(javaagent ),使用代理来动态修改字节码文件(由于Android虚拟机并不支持所以本专题不会再做介绍,在Android中可以使用aspectJ来实现类似这个级别的功能)
RUNTIME代表运行时级别,注解存在源码,字节码与Java虚拟机中,主要用于运行时反射获取相关信息,许多框架如OrmLite就是使用这个级别的注解,这个级别的框架额外的效率损耗发生在程序运行时
@Target
限制注解的元素种类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @
interface Override{
}
@Inherited
让子类类对象使用getAnnotations()反射获取父类被@Inherited修饰的注解
@Inherited
@Retention(RetentionPolicy.Runtime)
@interface Inheritable{
}
@interface UnInheritable{
}
public class Test{
@UnInheritable
@Inheritable
public static class Super{
}
public static class Sub extends Super {
}
public static void main(String... args){
Super instance=
new Sub();
System.out.println(Arrays.toString(instance.getClass().getAnnotations()));
}
}
转载请注明原文地址: https://ju.6miu.com/read-676082.html