注解(Annotation)
Annotation——注解
comment——注释
一、 什么是注解
JDK5.0引入
-
作用
- 不是程序本身,可以对程序作出解释(同comment)
- 可以被其他程序(如编译器)读取
-
格式
-
@注释名+(参数)
@SuppressWarnings(value="unchecked")
-
-
使用场景
-
相当于额外的辅助信息
-
通过反射机制实现对这些内置数据的访问
-
二、 内置注解
-
SuppressWarnings
三、元注解
meta-annotation——元注解
负责注解其他注解
java.lang.annotation包中
-
@Target——用于描述注解可以在哪里使用
-
@Retention——描述注解的声明周期
- SOURCE(源码) < CLASS(类) < RUNTIME(运行时-默认)
-
@Documented——文档注释javadoc
-
@Inherited
@MyAnnotation public class Test02 { @MyAnnotation public void test() { } } //定义一个注解 //Target——表示注解可以使用的范围 @Target(value = {ElementType.METHOD,ElementType.TYPE})//类与方法有效 //Retention——表示注解什么地方有效——SOURCE源码、RUNTIME运行时有效、CLASS编译有效 @Retention(value = RetentionPolicy.CLASS)//运行时有效 //Document——表示是否将注解生成在JAVAdoc中 @Documented //Inherited——表示子类可以继承父类的注解 @Inherited @interface MyAnnotation { }
四、自定义元注解
@interface
-
多个参数
public class Test03 { //如果没有default,在用注解的时候要填写参数,name、age、id、bohhy都要填写完整 //name定义了default默认值,也可以显示定义name = "小明" @MyAnnotation1(name = "小明",id = 101) void test() { } } //自定义注解 @Target(value = ElementType.METHOD) @Retention(value = RetentionPolicy.RUNTIME) @interface MyAnnotation1{ String name() default ""; int age() default 0; int id() default -1; String[] hobby() default {"唱歌","跳舞"}; } -
如果只有一个参数
public class Test03 { @MyAnnotation2(100)//2.在使用的时候可以省略参数名如:id = 101 void test() { } } //自定义注解 @Target(value = ElementType.METHOD) @Retention(value = RetentionPolicy.RUNTIME) @interface MyAnnotation2{ int value() default 0;//1.将唯一的一个参数命名为value }

浙公网安备 33010602011771号