注解
注解(Annotation),也叫做元注解,用于为 Java 代码提供元数据。在JDK1.5中添加到Java特性中。在代码中,注解不会直接影响到你的代码执行,而且使代码更加简洁明了。注解的语法比较简单,一般是用@符号作为开头。
注解按运行机制分成三类:
- 源码注解:只在源码中存在,编译后不存在;
- 编译时注解:源码和编译后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings);
- 运行时注解:能在程序运行时起作用(如spring的依赖注入);
元注解
在@Override 注解的定义中:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
其中@Target和@Retention就是元注解,元注解一般用于指定某个注解的生命周期以及作用目标等信息。
在Java中有以下四个元注解:
- @Target:注解的作用目标
- @Retention:注解的生命周期
- @Documented:注解是否应当被包含在JavaDoc文档中
- @Inherited:是否允许子类继承该注解
Java中的三个内置注解
在Java中内置的三个注解,他们分别是:
- @Override
- @Deprecated
- @SuppressWarnings
@Override 的定义如下:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Override 注解是一种典型的标注式注解,仅被编译器可知,编译器在对 java 文件进行编译成字节码的过程中,一旦检测到某个方法上被修饰了该注解,就会去匹对父类中是否具有一个同样方法签名的函数,如果不是,自然不能通过编译。
@Deprecated 的定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@Deprecated 依然是一种『标记式注解』,永久存在,可以修饰所有的类型,作用是,标记当前的类或者方法或者字段等已经不再被推荐使用了,可能下一次的 JDK 版本就会删除。
@SuppressWarnings 的定义如下:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is <i>not</i> an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* <p> The string {@code "unchecked"} is used to suppress
* unchecked warnings. Compiler vendors should document the
* additional warning names they support in conjunction with this
* annotation type. They are encouraged to cooperate to ensure
* that the same names work across multiple compilers.
* @return the set of warnings to be suppressed
*/
String[] value();
}
@SuppressWarnings 注解主要用来压制 java 的警告,代码的最后有一个value属性需要主动传值,value代表的是需要被压制的警告类型。
自定义注解
package com.flypie.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/* @Target,@Retention,@Inherited,@Documented
* 这四个是对注解进行注解的元注解,负责自定义的注解的属性
*/
@Target({ElementType.TYPE,ElementType.METHOD}) //表示注解的作用对象,ElementType.TYPE表示类,ElementType.METHOD表示方法
@Retention(RetentionPolicy.RUNTIME) //表示注解的保留机制,RetentionPolicy.RUNTIME表示运行时注解
@Inherited //表示该注解可继承
@Documented //表示该注解可生成文档
public @interface Design {
String author(); //注解成员,如果注解只有一个成员,则成员名必须为value(),成员类型只能为原始类型
int data() default 0; //注解成员,默认值为0
}
—————————分割线————————————————————————————————
以上内容都是目前所理解的,非最终版本,会根据工作和学习的深入慢慢加深理解,更新在上面(2020.5.26版)。