Annotation——注解
comment——注释
JDK5.0引入
作用
格式
@注释名+(参数)
@SuppressWarnings(value="unchecked")
使用场景
相当于额外的辅助信息
通过反射机制实现对这些内置数据的访问
SuppressWarnings
meta-annotation——元注解
负责注解其他注解
java.lang.annotation包中
@Target——用于描述注解可以在哪里使用
@Retention——描述注解的声明周期
@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
}
原文:https://www.cnblogs.com/Sheltonz/p/14117230.html