1. What is a duplicate annotation?
Allows multiple uses of the same annotation on the same declared type (class, property, or method)
2. A simple example
Before Java 8, there were also solutions for reusing annotations, but the readability was not very good, such as the following code:
Copy the code code as follows:
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseOldVersion {
@Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
public void doSomeThing(){
}
}
Use another annotation to store repeated annotations. When using it, use the storage annotation Authorities to extend the repeated annotations. Let's take a look at the approach in Java 8:
Copy the code code as follows:
@Repeatable(Authorities.class)
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseNewVersion {
@Authority(role="Admin")
@Authority(role="Manager")
public void doSomeThing(){ }
}
The difference is that when creating the repeated annotation Authority, add @Repeatable to point to the stored annotation Authorities. When using it, the Authority annotation can be reused directly. From the above example, we can see that the approach in Java 8 is more suitable for conventional thinking and is more readable.
3. Summary
JEP120 doesn't have much content, it's a small feature just to improve code readability. This time Java 8 has made two improvements to annotations (JEP 104, JEP120). I believe annotations will be used more frequently than before.