文章目录
1. 定义
java提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法。(java1.5之后有的)
2. JDK中常见的注解
2.1 @Override
告诉编译器该方法覆盖父类中的方法,用于编译检查。只有在编译前阶段有效
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
2.2 @Deprecated
标记该方法已经过时,但是有可能之前有人用(这个方法不能删除)该注解提醒使用该方法的人不要用这个方法。但是仍然可以用.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
2.3 @SuppressWarnings()
忽略警告,比如@SuppressWarnings(“deprecated”)表示忽略过时警告
@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();
}
3. 注解的分类
3.1 按照运行机制分
在上面的源码注解中可以看到@Retention(RetentionPolicy.SOURCE),
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
}
3.1.1 源码注解
注解只在源码中存在,编译成.class文件时注解就不存在了。
3.1.2 编译时注解
注解在源码和.class文件中都存在注解信息
3.1.3 运行时注解
在运行阶段还存在的注解,可能会影响运行时逻辑。
4. 自定义注解语法
不允许map
value那一条是规定
接口实现方式不起作用,只能类继承
5. 解析注解
通过反射获取类,函数或成员上的运行时注解信息,从而实现动态控制运行时的逻辑。