Repeatable annotations

Annotate the declaration of the annotation with @Repeatable to denote that the annotation can be applied multiple times at one place. The parameter to this annotation is an annotation type that should have a parameter of type, which is an array of this annotation. Don't try to understand! I'll give an example instead. I already have, in fact: we have @PoweredDevices. It has an argument that is an array of @ParameteredPoweredDevice. Consider that we now annotate this @interface as the following:

... 
@Repeatable(PoweredDevices.class)
public @interface ParameteredPoweredDevice {
...

Then, we can simplify the use of @ParameteredPoweredDevice. We can repeat the annotation multiple times and the Java runtime will automatically enclose it in the wrapping class, which, in this case, is @PoweredDevices. In this case, the following two will be equivalent:

... 
@ParameteredPoweredDevice("1956")
@ParameteredPoweredDevice({"1968", "2018"})
public class NeedPowercord implements ConsistencyChecker {
...

@PoweredDevices(
{@ParameteredPoweredDevice("1956"), @ParameteredPoweredDevice({"1968", "2018"})}
)
public class NeedPowercord implements ConsistencyChecker {
...

The reason for this complex approach is again an example of backward compatibility that Java strictly follows. Annotations were introduced in Java 1.5 and repeatable annotations have been available only since version 1.8. We will soon talk about the reflection API that we use to handle the annotations during runtime. This API in the java.lang.reflect.AnnotatedElement interface has a getAnnotation(annotationClass) method, which returns an annotation. If a single annotation can appear more than once on a class, method, and so on, then there is no way of calling this method to get all the different instances with all the different parameters. Backward compatibility was ensured by introducing the containing type that wraps the multiple annotations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.237