Java 什么是注解及注解原理详细介绍
1、注解是针对Java编译器的说明。
可以给Java包、类型(类、接口、枚举)、构造器、方法、域、参数和局部变量进行注解。Java编译器可以根据指令来解释注解和放弃注解,或者将注解放到编译后的生成的class文件中,运行时可用。
2、注解和注解类型
注解类型是一种特殊的接口类型,注解是注解注解类型的一个实例。
注解类型也有名称和成员,注解中包含的信息采用键值对形式,可以有0个或多个。
3、Java中定义的一些注解:
@Override 告诉编译器这个方法要覆盖一个超类方法,防止程序员覆盖出错。
@Deprecated 这个标识方法或类(接口等类型)过期,警告用户不建议使用。
@SafeVarargs JDK7新增,避免可变参数在使用泛型化时候警告”执行时期无法具体确认参数类型“,当然,也可以用@SuppressWarnings来避免检查,显然后者的抑制的范围更大。
@SuppressWarnings(value={"unchecked"}) 抑制编译警告,应用于类型、构造器、方法、域、参数以及局部变量。 value是类型数组,有效取值为:
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)
javadoc, to suppress warnings relative to javadoc warnings
nls, to suppress warnings relative to non-nls string literals
null, to suppress warnings relative to null analysis
rawtypes, to suppress warnings relative to usage of raw types
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, to suppress warnings relative to incorrect static access
static-method, to suppress warnings relative to methods that could be declared as static
super, to suppress warnings relative to overriding a method without super invocations
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 and dead code
4、注解的定义
使用 @interface 关键字声明一个注解
public @interface MyAnnotation1
注解中可以定义属性
String name default “defval”;
value是注解中的特殊属性
注解中定义的属性如果名称为 value, 此属性在使用时可以省写属性名
例如,声明一个注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno1 {
String msg();
int value();
}