1 注解Annotation
1.1 注解入门
什么是注解:
注解可以被程序识别,注释(comment)
Annotation是从JDK5.0开始引入的
Annotation的作用
不是程序本身,可以对程序作出解释(与comment相同)
可以被其他程序(比如编译器)读取
Annotation的格式
注解是以“@注释名”在代码中存在的,还可以添加一些参数值
例如:@SuppressWarnings(value=“unchecked”)
Annotation在哪里使用
可以附加在package, class, method, field 等上面,相当于给他们添加了额外的辅助信息,且可以通过反射机制编程实现对这些元数据的访问
1.2 内置注解
@Override:定义在 java.lang.Override 中,此注释只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明
@Deprecated:定义在 java.lang.Deprecated中,此注释可以用于修饰方法、属性、类,表示不鼓励程序员使用这样的元素,通常是因为它很危险或者存在更好地选择
@SuppressWarnings:定义在 java.lang.SuppreWarnings 中,用来抑制编译时的警告信息
带有参数:
1. @SuppressWarnings("all")
2. @SuppressWarnings("unchecked")
3. @SuppressWarnings(value={"unchecked", "deprecation"})
1.3 元注解
元注解的作用就是负责注解其他注解,java 定义了4个标准的meta-annotation类型,他们被用来提供对其他 annotation 类型作说明
这些类型和他们所支持的类在 java.lang.annotation 包中可以找到(@Target, @Retention, @Documented, @Inherited)
@Target:用于描述注解的使用范围,即被描述的注解可以用在什么地方
@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
(SOURCE < CLASS < RUNTIME)
@Document:说明该注解江北包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
package annotation;
import java.lang.annotation.*;
// 测试元注解
public class TestDemo01 {
// @Override
@MyAnnotation
public void test(){
}
}
// 定义一个元注解
// Target 表示该注解可以使用在什么地方
@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE})
// Retention 表示该注解在什么地方还有效
@Retention(value = RetentionPolicy.RUNTIME)
// Documented 表示是否将注解生成在java.doc中
@Documented
// Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
1.4 自定义注解
使用**@interface**自定义注释时,自动继承了 java.lang.annotation.Anotation接口
分析
1. @interface 用来声明一个注解,格式:public @ interface 注解名 {定义内容}
2. 其中的每一个方法实际上是声明了一个配置参数
3. 放的名称就是参数的名称
4. 返回值类型就是参数的类型(返回值只能是基本类型,Class, String, enum)
5. 可以通过 default 来声明参数的默认值
6. 如果只有一个参数成员,一般参数名为value
7. 注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0 作为默认值
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义注解
public class TestDemo03 {
// 注解可以显式赋值,也可以使用默认值
@MyAnnotation2(name = "haoqiqi")
public void test(){
}
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
// 注解的参数 : 参数类型 + 参数名() " + default 默认值";
String name() default "aaa";
int age() default 0;
int id() default -1; // 若默认值是-1,代表不存在
String[] schools() default {"SEU"};
}