首先,我们定义一个包装注解,它包括了一个实际注解的数组
- @interface Hints {
- Hint[] value();
- }
- @Repeatable(Hints.class)
- @interface Hint {
- String value();
- }
只要在前面加上注解名:@Repeatable,Java 8 允许我们对同一类型使用多重注解:
变体1:使用注解容器(老方法):
- @Hints({@Hint("hint1"), @Hint("hint2")})
- class Person {}
变体2:使用可重复注解(新方法):
- @Hint("hint1")
- @Hint("hint2")
- class Person {}
使用变体2,Java编译器能够在内部自动对@Hint进行设置。这对于通过反射来读取注解信息来说,是非常重要的。
- Hint hint = Person.class.getAnnotation(Hint.class);
- System.out.println(hint); // null
- Hints hints1 = Person.class.getAnnotation(Hints.class);
- System.out.println(hints1.value().length); // 2
- Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
- System.out.println(hints2.length); // 2
尽管我们绝对不会在Person类上声明@Hints注解,但是它的信息仍然可以通过getAnnotation(Hints.class)来读取。并且,getAnnotationsByType方法会更方便,因为它赋予了所有@Hints注解标注的方法直接的访问权限。
- @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
- @interface MyAnnotation {}