Java注解
Java注解:元数据的另外一种表现形式,功能等同于XML,为程序提供数据,本身不属于程序,注解通常有以下用途:
- 提供编译信息,常见的警告支持等等。
- 编译时和部署时操作,通过编译时通过注解信心来生成代码、XML文件等。
- 运行时处理,运行时检查
注解使用格式:Java 注解的基本格式
- 最简单的注解,@字符告诉编译器为一个注解
@Entity
- 熟悉的注解元素
@Override
void mySuperMethod() { ... }
- 包含元素的注解
@Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
class MyClass() { ... }
注解类型:指定注解可以出现的场合。
- 用于实例创建表达式
new @Interned MyObject();
- 用于类型转换
myString = (@NonNull String) str;
- Implements 约定
class UnmodifiableList<T> implements
@Readonly List<@Readonly T> { ... }
- 异常声明
void monitorTemperature() throws
@Critical TemperatureException { ... }
定义注解类型:
场景模拟:使用注解替换Java注释。
使用注视的Java代码
public class T1{
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
定义注解:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
替换后的Java代码:
@ClassPreamble(
author="XiaoFen",
currentRevision=1,
lastModified="二〇一六年六月九日 09:24:14",
reviewers={""},
date = "2016年6月9日 09:24:55")
public class T1 {
}
预定义的注解类型:
@Deprecated,标识被废弃。常见的java.util.Date类中过时的方法使用了如下代码标识一个构造器的废弃。
@Deprecated
public Date(String s) {
this(parse(s));
}
@Override,标识从超类中重写方法,一般发生在继承中。java.sql.Date重写java.util.Date的toInstant方法。
@Override
public Instant toInstant() {
throw new java.lang.UnsupportedOperationException();
}
@SuppressWarnings,抑制一个编译时警告。
@SuppressWarnings("deprecation")
public LocalDate toLocalDate() {
return LocalDate.of(getYear() + 1900, getMonth() + 1, getDate());
}
元注解:可以被用来修饰注解的注解元素,常见的如下。
- @Retention,修饰一个注解如何被存储,仅有一个value属性可能的值如下。
RetentionPolicy.SOURCE,标识注解元素仅保留在源码级别,编译时被忽略。
RetentionPolicy.CLASS,编译时保留,JVM运行时忽略。
RetentionPolicy.RUNTIME,JVM运行时使用,可以在运行时读取。
- @Documented,表明该注解被javadoc工具记录,默认情况下对注解的注释不会在javadoc中生成。
- @Target,指定当前注解元素允许出现的位置。只有一个value属性可能为如下中的若干。
ElementType.ANNOTATION_TYPE can be applied to an annotation type.
ElementType.CONSTRUCTOR can be applied to a constructor.
ElementType.FIELD can be applied to a field or property.
ElementType.LOCAL_VARIABLE can be applied to a local variable.
ElementType.METHOD can be applied to a method-level annotation.
ElementType.PACKAGE can be applied to a package declaration.
ElementType.PARAMETER can be applied to the parameters of a method.
ElementType.TYPE can be applied to any element of a class.
- @Inherited,申明该注解可以从超类继承。
- @Repeatable,该注解可以在一个元素上重复出现。