注解(Annotation)的概述:
- 其实就是代码中特殊的标记,可以在类加载时候,运行时候被读取,并执行相应的代码,
- 可以像修饰符一样被使用,可用于修饰包,类,构造器,方法,成员变量,参数,局部变量的声明,这些信息被保存在Annotation的"name=value"中;
- 注解就是代替javaEE旧版中遗留的繁冗代码和xml配置等
常见的Annotation事例:
示例一:生成文档相关的注释
事例二:在编译时进行格式检查(jdk内置的基本注解)
事例三:跟踪代码依赖性,实现替代配置文件功能
例如 servlet 提供了注解,不再需要web.xml配置
如何自定义注解?
第一步:注解声明为 @interface 进行声明
- 类型只能是 8大基本数据类型,String类型,class类型,enum类型,Annotation类型以上所有类型的数组.
- 指定 Annotation 成员变量的时候可以指定初始值可使用 default 关键字
- 内部定义成员,通常使用 value表示
- 如果自定义注解没有成员,表明是一个标识的作用
注意: 如果成员有成员 ,在使用注解的时候,需要指明成员的值
自定义注解必须配上注解的信息处理流程(使用反射)才有意义