什么是注解
-
Annotation是从JDK5.0开始引入的新技术.
-
Annotation的作用:
-
Annotation的格式:
-
注释是以“@注释名”在代码中存在的,还可以添加一些参数值.例如:@SuppressWarnings(value="unchecked").
-
Annotation在哪里使用?
-
可以附加在package,class,method,field等上面,相当于给他们添加了额外的辅助信息.
-
我们可以通过反射机制编程实现对这些元数据的访问.
内置注解
元注解
-
-
这些类型和它们所支持的类在java.lang.annotation包中可以找到.(@Target,@Retention,@Documented,@Inherited)
-
@Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方).
-
@Retention: 表示需要在什么级别保存该注释信息,用于描述注解的生命周期.
-
(RUNTIME > CLASS > SOURCE)
-
@Documented:说明该注解将被包含在javadoc中.
-
@Inherited:说明子类可以继承父类中的该注释.
package com.chao.annotation;
import java.lang.annotation.*;
//测试元注解
@MyAnnotation
public class Test02 {
public void test(){}
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方.
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方还有效.
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在javadoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
自定义注解
-
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口.
-
分析:
-
@interface用来声明一个注释,格式:public @ interface 注解名(定义内容).
-
其中的每一个方法实际上是声明了一个配置参数.
-
方法的名称就是参数的名称.
-
返回值类型就是参数的类型(返回值只能是基本类型,Class,String,enum).
-
可以通过default来声明参数的默认值.
-
如果只有一个参数成员,一般参数名为value.
-
注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值.
package com.chao.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义注解
public class Test03 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation2(age = 18,name = "王超")
public void test(){}
@MyAnnotation3("王超")
public void test2(){
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数 : 参数类型 + 参数名();
String name() default "";
int age();
int id() default -1;//如果默认值为-1,代表不存在,indexof, 如果找不到就返回-1
String[] schools() default {"西北大学,西工大,西安工业大学"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}