Repeat annotations and type annotations
Since annotations were introduced in JDK1.5, annotations have become very popular and are widely used in various frameworks and projects. One big limitation of annotations, however, is that you cannot use the same annotation more than once in the same annotation. JDK8 introduces the concept of repeated annotations, allowing the same annotation to be used multiple times in the same place. Repeatable annotation is defined in JDK8 using the @REPEATable annotation.
Repeated notes
Repeat the steps for using annotations:
- Define duplicate annotation container annotations
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTests {
RepeatableMyTests[] value();
}
Copy the code
- Define a repeatable annotation
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyTests.class)
public @interface RepeatableMyTests {
String value(a);
}
Copy the code
- Configure repeated annotations
@RepeatableMyTests("11")
@RepeatableMyTests("12")
public class Demo01 {
@RepeatableMyTests("1")
@RepeatableMyTests("2")
public void test01(a) {}}Copy the code
- Parse repeated annotations
public static void main(String[] args) throws NoSuchMethodException {
// Parse repeated annotations
//getAnnotationsByType a new API for getting repeated annotations
// Get repeated annotations on the class
RepeatableMyTests[] annotationsByType = Demo01.class.getAnnotationsByType(RepeatableMyTests.class);
for (RepeatableMyTests repeatableMyTest : annotationsByType) {
System.out.println(repeatableMyTest);
}
// Get repeated comments on methods
RepeatableMyTests[] annotationsByType2 = Demo01.class.getMethod("test01").getAnnotationsByType(RepeatableMyTests.class);
for(RepeatableMyTests repeatableMyTest : annotationsByType2) { System.out.println(repeatableMyTest); }}Copy the code
Type annotations
JDK8 adds two new types for @target meta-annotations: TYPE_PARAMETER and TYPE_USE
TYPE_PARAMETER: indicates that the annotation is written in the declaration of type parameters, such as:
/ / define
@Target(ElementType.TYPE_PARAMETER)
public @interface TypeParam {
}
/ / use
public <@TypeParam E extends Integer> void testo1(a) {}Copy the code
TYPE_USE: Indicates that the annotation can be used wherever the class is used
define@Target(ElementType.TYPE_USE)
public @interface Notnull {
}
/ / use
private @Notnull int index =0;
public void test02(@Notnull String str, @Notnull int a){
@Notnull int index =0;
}
Copy the code