1.注解概述
Annotation(注解)是 Java 提供的一种对元程序中元素关联信息和元数据(metadata)的途径和方法。Annatation(注解)是一个接口,程序可以通过反射来获取指定程序中元素的 Annotation对象,然后通过该 Annotation 对象来获取注解中的元数据信息。
2.内置注解
package AnnotationAndComment;
import java.util.ArrayList;
import java.util.List;
public class TestAnnotation extends Object{
//@Override 重写的注解
@Override
public String toString() {
return super.toString();
}
@Deprecated //过时的,不推荐使用但可以使用,或者有更好的方法
public static void test(){
System.out.println("Deprecated");
}
//镇压警告
@SuppressWarnings("all")
public void test01(){
List list=new ArrayList();
}
public static void main(String[] args) {
test();
}
}
3.元注解
元注解的作用是负责注解其他注解。 Java5.0 定义了 4 个标准的 meta-annotation 类型,它们被用来提供对其它 annotation 类型作说明。
@Target 修饰的对象范围
@Target说明了Annotation所修饰的对象范围: Annotation可被用于 packages、types(类、接口、枚举、Annotation 类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch 参数)。在 Annotation 类型的声明中使用了 target 可更加明晰其修饰的目标
@Retention 定义 被保留的时间长短
Retention 定义了该 Annotation 被保留的时间长短:表示需要在什么级别保存注解信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效),取值(RetentionPoicy)由:
„ SOURCE:在源文件中有效(即源文件保留)
„ CLASS:在 class 文件中有效(即 class 保留)
„ RUNTIME:在运行时有效(即运行时保留)
@Documented 描述-javadoc
@ Documented 用于描述其它类型的 annotation 应该被作为被标注的程序成员的公共 API,因此可以被例如 javadoc 此类的工具文档化。
@Inherited 阐述了某个被标注的类型是被继承的
@Inherited 元注解是一个标记注解,@Inherited 阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited 修饰的 annotation 类型被用于一个 class,则这个 annotation 将被用于该class 的子类
package AnnotationAndComment;
import java.lang.annotation.*;
//测试元注解
public class Test01 {
@MyAnnotation
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{
}
4.自定义注解
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
- @interface用来声明一个注解,格式:public @interface 注解名{定义内容}
- 其中的每一个方法实际上是声明了一个配置参数
- 方法的名称就是参数的名称
- 返回值类型就是参数的类型(只能是基本类型,Class,String,enum)
- 可以通过default来声明参数的默认值
- 如果只有一个参数成员,一般参数名为value
- 注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值
package AnnotationAndComment;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义注解
public class Test02 {
//注解可以显示赋值,没有默认值就必须给注解赋值
@MyAnnotation2(name="11",schools = "22")
public void test(){
}
@MyAnnotation3("33")
public void test1(){
}
}
@Target(value ={ ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型+参数名()
String name();
int age() default 0;
int id() default -1;//代表不存在
String[] schools();
}
@Target(value ={ ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}