注解
1、什么是注解
不是程序本身,可以对程序做出一定的解释
可以被其他的程序读取
格式
注解是以@注释名 在代码中存在的,还可以加一些参数值
在那里使用
可以在package、class、method、field (包、类、方法、属性)上面
2、内置注解
@Override:重写
@Override
public String toString() {
return null;
}
@Deprecated 表示不鼓励程序员只用这个元素,有更好的选择
@Deprecated
public static void test() {
System.out.println("方法过时或者危险");
}
public static void main(String[] args) {
test(); // 方法上会出现一个横杠,表示方法过时,但是还是可以使用的
}
@SuppressWarnings 抑制编译时的警告信息
一般不建议使用
3、元注解
负责解释其他注解的注解,java只有四个元注解
@Target
表示注解的使用范围
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
里面只有一个参数 ElementType[] value();
ElementType 是一个枚举类,里面定义了很多的范围参数
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
使用:(自定义注解)
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@interface MyAnotation{
}
@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.
*/
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,
/**
* 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.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented
说明这个注解是否要生成在Javadoc文档中
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Inherited
说明子类可以继承父类中的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
4、自定义注解
使用关键字@interface来声明一个注解
如果只有一个参数,一般用value来作为参数的名字,参数是以()结尾的,不是方法是参数
使用default来设置一个注解的默认值,一般是用"" 或者0老作为参数的默认值,如果默认值是-1,就是不存在
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnotation{
String value() default "";
}