示例一:生成文档相关的注解
示例二:在编译时进行格式检查(JDK内置的三个基本注解)
示例三:跟踪代码依赖性,实现替代配置文件功能
参照@SuppressWarnings定义
如果注解有成员,在使用注解时,需要指明成员的值。
自定义注解必须配上注解的信息处理流程(使用反射)才有意义。
自定义注解通常都会指明两个元注解:Retention、Target
元注解:对现有的注解进行解释说明的注解
@Inherited
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
String value() default "hello";
}
@Test
public void testGetAnnotation() {
Class<Student> studentClass = Student.class;
Annotation[] annotations = studentClass.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i]);
}
}
可重复注解:
//jdk8之前的写法:
//@MyAnnotations({@MyAnnotation("hi"),@MyAnnotation("abc")})
@MyAnnotation("hi")
@MyAnnotation("abc")
类型注解:
class Generic<@MyAnnotation T>{
public void show() throws @MyAnnotation RuntimeException{
ArrayList<@MyAnnotation String> list = new ArrayList<>();
int num = (@MyAnnotation int)10L;
}
}
原文:https://www.cnblogs.com/koito/p/14887511.html