Java 注解

本文最后更新于:2024年3月18日 凌晨

Java 注解

  • Annotation是从JDK5.0开始引入的新技术。
  • 作用
    • 不是程序本身,但是可以对程序作出解释。
    • 可以被其他程序(如编译器)读取。
  • 格式:注解是以@注释名在代码中存在的,还可以添加一些参数值,例如@SuppressWarnings(value = "unchecked")
  • 使用方式:注解可以附加在package,class,method,field等上面,相当于给它们添加了额外的辅助信息,可以通过反射机制实现对这些元数据的访问。

内置注解

@Override

  • Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:
    • The method does override or implement a method declared in a supertype.
    • The method has a signature that is override-equivalent to that of any public method declared in Object.
1
2
3
4
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

实例

1
2
3
4
@Override
public String toString() {
return "Test{}";
}

@Deprecated

  • A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code.
1
2
3
4
5
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

实例

1
2
3
4
@Deprecated
public static void test() {
System.out.println("Deprecated");
}

@SuppressWarings

  • Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element). Note that the set of warnings suppressed in a given element is a superset of the warnings suppressed in all containing elements. For example, if you annotate a class to suppress one warning and annotate a method to suppress another, both warnings will be suppressed in the method.
  • As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.
1
2
3
4
5
6
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}

  • 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 not 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.
  • The string “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.
  • Returns: the set of warnings to be suppressed
关键字 用途
all to suppress all warnings
boxing to suppress warnings relative to boxing/unboxing operations
cast to suppress warnings relative to cast operations
dep-ann to suppress warnings relative to deprecated annotation
deprecation to suppress warnings relative to deprecation
fallthrough to suppress warnings relative to missing breaks in switch statements
finally to suppress warnings relative to finally block that don’t return
hiding to suppress warnings relative to locals that hide variable
incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
nls to suppress warnings relative to non-nls string literals
null to suppress warnings relative to null analysis
rawtypes to suppress warnings relative to un-specific types when using generics on class params
restriction to suppress warnings relative to usage of discouraged or forbidden references
serial to suppress warnings relative to missing serialVersionUID field for a serializable class
static-access o suppress warnings relative to incorrect static access
synthetic-access to suppress warnings relative to unoptimized access from inner classes
unchecked to suppress warnings relative to unchecked operations
unqualified-field-access to suppress warnings relative to field access unqualified
unused to suppress warnings relative to unused code

实例

1
2
3
4
5
@SuppressWarnings(value={"unchecked", "rawtypes"})
public void addItems(String item){
List items = new ArrayList();
items.add(item);
}

元注解

  • 元注解的作用就是负责注解其他注解,Java定义了4个标准的meta-annotation类型,它们被用来提供对其他annotation类型作说明。
  • 这些类型和它们所支持的类在java.lang.annotation包中可以找到:
    • @Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
    • @Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE < CLASS < RUNTIME)
    • @Document:说明该注解将被包含在javadoc中。
    • @Inherited:说明子类可以继承父类中的该注解。

@Target

  • Indicates the contexts in which an annotation type is applicable. The declaration contexts and type contexts in which an annotation type may be applicable are specified in JLS 9.6.4.1, and denoted in source code by enum constants of java.lang.annotation.ElementType.
  • ElementType包含了所有的使用范围:
    • ElementType.TYPE:说明该注解只能被声明在一个类前。
    • ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
    • ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
    • ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。
    • ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
    • ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
    • ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
    • ElementType.PACKAGE:说明该注解只能声明在一个包名前。
1
2
3
4
5
6
7
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}

  • Returns an array of the kinds of elements an annotation type can be applied to.

实例

1
2
3
4
5
6
7
8
@AnnotationTest
class Test {
}

@Target(value = {ElementType.METHOD, ElementType.TYPE})
@interface AnnotationTest {

}

@Retention

  • Indicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS.
  • A Retention meta-annotation has effect only if the meta-annotated type is used directly for annotation. It has no effect if the meta-annotated type is used as a member type in another annotation type.
  • RetentionPolicy中包含了所有的生命周期。
    • RetentionPolicy.SOURCE:注解只保留在源文件中。
    • RetentionPolicy.CLASS :注解保留在class文件中,在加载到JVM虚拟机时丢弃。
    • RetentionPolicy.RUNTIME:注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解。
1
2
3
4
5
6
7
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}

  • Returns the retention policy.

实例

1
2
3
4
5
6
7
8
@AnnotationTest
class Test {
}

@Retention(value = RetentionPolicy.RUNTIME)
@interface AnnotationTest {

}

@Document

  • Indicates that annotations with a type are to be documented by javadoc and similar tools by default. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.
1
2
3
4
5
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

@Inherit

  • Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation.
  • Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.
1
2
3
4
5
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

自定义注解

  • @interface用来声明一个注解。
1
2
3
@interface 注解名 {
String[] value();
}
  • 其中的每一个方法实际上是声明了一个配置参数,方法的名称就是参数的名称,返回值类型就是参数的类型。

默认值

1
2
3
@interface 注解名 {
int value() default 0;
}
  • 可以通过default声明参数的默认值,如果只有一个参数成员,一般参数名为value
  • 定义注解元素时,经常使用空字符串或0作为默认值。