系统自带的3种Annotation
@Override | 确保覆写正确,如果在@Override后的方法不是正确的覆写就会报错 |
---|---|
@Deprecated | 不赞成使用,被此注释的方法或属性等等 会产生warning |
@SuppressWarning | 压制warning,@SuppressWarning(关键字) |
@SuppressWarning中的关键字
deprecation | 使用了不赞成的类,方法,属性等等 |
---|---|
unchecked | 执行了为检查的转换时警告,如:泛型中没有指定泛型类型 |
fallthrough | 在switch中没有break |
path | 类路径,源文件路径不存在时的警告 |
serial | 可序列化的类确实serialVersionUID定义时的警告 |
finally | 任何finally语句不能正常完成的警告 |
all | 以上所有警告 |
设置@SuppressWarning时可以@SuppressWarning("all")也可以@SuppressWarning(value="all")
自定义Annotation
public @interface MyAnnotation{
}
- 这就定义了一个Annotation
public @interface MyAnnotation{
public String value();
}public @interface MyAnnotation{
public String value();
}
- 这样就可以接收一个变量,通过@MyAnnotation("lalala")或@MyAnnotation(value="lalala")来使用
public @interface MyAnnotation{
public String value();
public String key();
}
-
这样设置多个内容:key和String,通过@MyAnnotation(value="lalala",key="这是key")来使用
-
如果要向Annotation中的一个属性传递多个内容可以
public @interface MyAnnotation{ public String[] value(); }
-
通过@MyAnnotation(value={"lalala","hhhhh"})来使用
上面这样的代码,在你每次使用该注释时都要手动传参,传参错误就报错,太麻烦。可以象这样设置默认值
public @interface MyAnnotation{
public String value() defualt "默认的value";
public String key() defualt "默认的key";
}
通常使用枚举类来设置默认值
Retention设置保存范围
使用Retention注释 去注释一个 自定义注释类,这可以指定被注释的注释的保存范围
Retention有三种策略,定义在RetentionPolicy枚举中
SOURCE | 注释只会保存在java文件中,编译后不会存在class文件中 |
---|---|
CLASS(默认的) | 会存在java与class文件中,不会被加载到虚拟机中 |
RUNTIME | 会在java和class文件中,并会被加载到虚拟机中 |
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
public String value();
}
像这样指定范围
通过反射得到Annotation
Class类中存在一下几种方法
getAnnotation(注释的Class对象) | 得到指定的注释 |
---|---|
getAnnotations() | 返回此元素上的全部注释 |
getDeclaredAnnotations() | 返回此元素上的全部注释,不包括父类的 |
isAnnotation() | 判断这个类是否是注释 |
isAnnotationPresent(Annotation的子类的Class对象) | 判断一个元素是否是被指定的注释修饰 |
@Target设置注释位置
@Target(ElementType.Type)像这样就限制注释只能出现在接口、类、枚举、注解中
TYPE | 接口、类、枚举、注解 |
---|---|
FIELD | 字段、枚举的常量 |
METHOD | 方法 |
PARAMETER | 方法参数 |
CONSTRUCTOR | 构造函数 |
LOCAL_VARIABLE | 局部变量 |
ANNOTATION_TYPE | 注解 |
PACKAGE | 包 |
将ElementType中元素传入到@Target中,就可以指定范围
@Inherited
被@Inherited修饰的 注释类如果拿去注释另一个类,那么被注释的类被继承后,它的注释也会连带被继承
@Retention(value=RetentionPolicy.RUNTIME)
@Inherited
@interface B{}//定义一个注释
@B //用刚刚定义的注释来注解一个类
class shit{
}
class s extends shit{
}//s继承了shit0
public static void main(String[] args) throws Exception {
for(var i:s.class.getAnnotations())//来用反射得到s类的注释并输出
System.out.println(i);
}
@cZip.B()//输出结果为这个,说明s就因为继承了shit类,也连带继承该注释
注:如果在声明Annotation的时候没有加上@Inherited注解的话0,则此Annotation是无法被继承的