Analysis of repeating annotations for new Java8 features

  • 2020-04-01 03:22:12
  • OfStack

1. What are repeated annotations

Allows multiple use of the same annotation for the same declaration type (class, property, or method)

2. A simple example

Before Java 8, there were solutions to reuse annotations, but they were not very readable, such as the following code:


public @interface Authority {
     String role();
}
public @interface Authorities {
    Authority[] value();
}
public class RepeatAnnotationUseOldVersion {

    @Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
    public void doSomeThing(){
    }
}

Duplicate annotations are stored by another annotation. When used, duplicate annotations are extended by storing annotations authority. Let's take a look at Java 8 again:


@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 duplicate annotation Authority, add @repeatable to point to the stored annotation Authority, and the Authority annotation can be reused directly when used. As you can see from the above example, the approach in Java 8 is more suitable for conventional thinking and a bit more readable

Third, summary

JEP120 doesn't have much to say, it's a small feature, just to improve the readability of the code. This time Java 8 has improved annotations in two ways (JEP 104,JEP120) and I believe they will be used more frequently than ever before.


Related articles: