1、JDK内置注解
注解都是定义在java.lang.Override下的
-
@Override:重写一个方法的注解
-
@Deprecated:表示不建议使用
-
@SuppressWarnings:镇压警告,需要传参
-
等等
2、自定义注解
@interface MyAnnotation{
}
3、元注解:元注解就是用来描述注解的注解
import java.lang.annotation.*;
@MyAnnotation
public class TestAnnotation {
}
//定义一个注解
@Target(value = {ElementType.METHOD,ElementType.TYPE}) //表示注解可以用在那些地方
@Retention(value = RetentionPolicy.RUNTIME) //表示注解在哪些地方有效
@Documented //表示是否将我们的注解生成在Javadoc中
@Inherited //子类可以继承父类的注解
@interface MyAnnotation{
}
4、自定义注解加上元注解
import java.lang.annotation.*;
//自定义注解
public class TestAnnotation{
//注解可以显式赋值,如果没有默认值则必须赋值
@MyAnnotation(name = "Hu",schools = {"新东方","蓝翔"})
public TestAnnotation(){}
}
//可以标注在类、方法、构造器上
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String name() default "张三"; //注解的参数定义:参数类型 + 参数名();
int age() default 3;
int id() default -1; //如果默认值为-1,代表不存在
String[] schools();
}