使用注解(Annotation)时要在前面加@符号,注解可以当作一个修饰符来修饰他支持的修饰的元素
@Override - 重写,该注解只能用于方法
@Deprecated - 已弃用,用在程序元素上,如某个类上或者某个方法上
@SuppressWarnings - 抑制编译器警告
@Target - 指定注解可以在哪些地方使用
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation interface
* can be applied to.
* @return an array of the kinds of elements an annotation interface
* can be applied to
*/
ElementType[] value();
}
@Retention - 指定注解作用范围,三种范围SOURCE,CLASS,RUNTIME
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
* 作用在源码层面(.java文件层面),会被编译器丢弃,即不会编译进.class文件中
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
* 作用在字节码层面(.class文件层面),会被编译器记录,即会编译进.class文件中,但不会被JVM保留,即运行
* 时被丢弃
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
* 作用在JVM层面(.class文件层面),会被编译器记录,即会编译进.class文件中,也会被JVM保留,即在JVM上运行时也能被反射
* 机制读取到
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented - 是否在JavaDoc里面体现
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Inherited - 子类会继承父类注解