注解的本质
注解本质上可以理解为类,里面只可以定义属性,不定义方法。但属性带小括号()。属性的数据类型的取值范围只能8种基本数据类型以及String,Enum,Class,annotations等数据类型,以及这一些类型的数组。
注解是Java5开始引入的新特征,用来:1、为程序的元素(类、方法、成员变量)加上更直观更明了的说明,2、编译器告诉编译器对它所注解代码做相应的操作,运行期告诉执行引擎对它所注解的代码做相应的操作。
注解的分类
jdk自带的注解:
- @Override 表明被注解的方法是对父类方法的重写
- @Deprecated 表明被注解的方法或类被弃用了,过时了
- @SuppressWarnings 表明忽略编译器对被注解的方法或类的警告
元注解:用来注解自定义注解的注解。
- @Documented 所注解的对象包含在生成的Javadoc文档中
- @Retention 所注释的注解的或生命周期,取值有:RetentionPolicy.SOURCE(只在编译期存在),RetentionPolicy.CLASS(在编译期和类加载过程中存在,注解的默认取值),RetentionPolicy.RUNTIME(存在于编译期,类加载过程和运行期)
- @Inherited 表明该注解可以被注解的类或接口的子类或子接口继承
- @Target 表明该注解作用的范围,取值有:
- ElementType.CONSTRUCTOR: 用于描述构造器
- ElementType.FIELD: 用于成员变量、对象、属性(包括enum实例)
- ElementType.LOCAL_VARIABLE: 用于局部变量
- ElementType.METHOD: 用于方法
- ElementType.PACKAGE: 用于包
- ElementType.PARAMETER: 用于参数
- ElementType.TYPE: 用于描述类、接口(包括注解类型) 或enum声明
自定义注解
代码举例:
@DemoAnnotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Target(ElementType.FIELD)
public @interface DemoAnnotation {
String value() default "嘿嘿";
}
@DemoTypeAnnotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Target(ElementType.TYPE)
public @interface DemoTypeAnnotation {
int no() default -1;
String description() default "this is a type annotation";
boolean necessary() default false;
}
DemoAnnotationTest
import com.example.shirodemo.annotation.annotation.DemoAnnotation;
import com.example.shirodemo.annotation.annotation.DemoTypeAnnotation;
import java.lang.reflect.Field;
@DemoTypeAnnotation(no = 1,description = "this is new description",necessary = true)
public class DemoAnnotationTest {
@DemoAnnotation
private String name;
public static void main(String[] args) throws NoSuchFieldException {
DemoAnnotation annotation = DemoAnnotationTest.class.getDeclaredField("name").getAnnotation(DemoAnnotation.class);
System.out.println("属性:name的注解值是:"+annotation.value());
DemoTypeAnnotation demoTypeAnnotation = DemoAnnotationTest.class.getAnnotation(DemoTypeAnnotation.class);
System.out.println("类DemoAnnotationTest的注解的no属性值:"+demoTypeAnnotation.no()+"\ndescription值:"+demoTypeAnnotation.description()+"\nnecessary值:"+demoTypeAnnotation.necessary());
Field field = DemoAnnotationTest.class.getDeclaredField("name");
System.out.println("name属性上存在DemoTypeAnnotation注解吗:"+field.isAnnotationPresent(DemoTypeAnnotation.class));
System.out.println("DemoAnnotationTest类上存在DemoTypeAnnotation注解吗:"+DemoAnnotationTest.class.isAnnotationPresent(DemoTypeAnnotation.class));
}
}