Java 注解
> Java 注解
1、什么是注解
Annotation作用
- 不是程序本身,但可以对程序作出解释。(和注释comment没什么区别)
- 可以被其他程序(编译器)读取
Annotation格式
-
注解以
@注释名存在,例如:
@SuppressWarnings(value="unchecked")
Annotation使用地址
-
注解附加在package、class、method等上面,相当于添加额外辅助信息。
![image-20210925152406549]()
2、常用注解
-
@Override 作用:重写
-
@Deprecated (不推荐使用)
-
@SuppressWarnings 作用:抑制警告信息
![image-20210925160830097]()

3、元注解(meta-annotation)
元注解作用
负责注解其他注解,java定义了以下四种标注的元注解
@Retention:描述注解的生命周期
@Target:描述注解的使用范围 (source<class<Runtime) 一般用最后runtime
@Documented:说明该注解被包含于javadoc中
@Inherited:说明子类可以继承父类的该注解
package com.li;
import java.lang.annotation.*;
import java.lang.reflect.Array;
@test01.MyAnnotion //该注解能够放在clsaa之前
public class test01 extends Object {
@Override
public String toString() {
return super.toString();
}
@Target(value = {ElementType.METHOD,ElementType.TYPE}) //描述了使用范围
@Retention(RetentionPolicy.RUNTIME) //描述了注解的使用周期
@interface MyAnnotion{
}
}
4、自定义注解
使用: @interface自定义注解时,自动继承Annotation接口

package com.li;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class text03 {
//可以显示赋值 若没有默认值则必须赋值
@annotion2(name = "nanjiang")
@annotion3("nanjiang") //只有单一值为value时 可直接写参数
public void test03(){
}
}
@Target({ElementType.TYPE,ElementType.METHOD}) //作用域在类 or 方法上
@Retention(RetentionPolicy.RUNTIME)
@interface annotion2{
//注解的参数 参数类型 + 参数名();
String name() default "nanjiang"; //default "nanjiang" 默认参数值
int id() default -1; //默认-1 代表不存在
}
@Target({ElementType.TYPE,ElementType.METHOD}) //作用域在类 or 方法上
@Retention(RetentionPolicy.RUNTIME)
@interface annotion3{
//注解的参数 参数类型 + 参数名();
String value() ; //只有一共变量 且为value时
}
Ps: 此篇博文内容参考于遇见狂神说。供读者阅读参考,感谢~!



浙公网安备 33010602011771号