1.元注解
作用:负责注解其它注解
@Target:用于描述注解的适用范围(被描述的注解可以用在什么地方)
@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
(SOURCE < CLASS < RUNTIME)===》在什么时候该注解有用
@Document:说明该注解将被包含在javadoc中
@Inheriter:说明子类可以继承父类中的该注解
package com.test.note;
import java.lang.annotation.*;
public class Test01 {
public void test(){
}
}
//Target 表示我们的注解可以用在哪些地方
@Target(value = {ElementType.TYPE,ElementType.METHOD}) //在类上面有效,在方法上面有效
//Retention 表示我们的注解在什么地方会有效
@Retention(value = RetentionPolicy.RUNTIME) //在运行时有效
//Documented 表示是否将我们的注解生成在JAVADoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnoation{
}
2.自定义注解
(1)@interface用来声明一个注解,格式:@interface 注解名{ 定义内容 }
(2)其中的每一个方法实际上是声明了一个配置参数
(3)方法的名称就是参数的名称
(4)返回值类型就是参数的类型(返回值只能是基本类型、Class、String、enum)
(5)可以通过default来声明参数的默认值
(6)如果只有一个参数成员,一般参数名为value,只有为value时方法或者类上面加注解是才可以省略:@MyAnnoation("张三"); 如果参数是 name ,则必须这样写@MyAnnoation ( name="张三" )
(7)注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值
package com.test.note;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@MyAnnoation2(age = 18)
public class Test02 {
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnoation2{
String name() default "";
int age();
int id() default -1; // 如果默认值为-1,代表不存在
String[] schools() default {"西部大开发大学","清华大学"};
}