Java 8 Repeating Annotation Explained in 5 minutes

At IDRSolutions, I have been working on our new JavaFX PDF viewer implementation. In doing so , I have been taking advantage of the new features in Java8. In my previous articles, I have explained Lambda Expression, Streams API, Default Methods and Method References. In this latest article in the series, we will be looking at Repeating Annotations…

What is Repeating Annotations?

Prior to Java8, it was forbidden to declare more than one annotation of the same type to the same location of a code. Java8 introduces the repeating annotation. This means same annotations can be repeated as much as you want at same locations.

Lets have a look at this code.

Prior to Java8, to have a repeated annotation, will have to group them in a container annotation

@Manufactures({
@Manufacturer(name =”BMW”),
@Manufacturer(name = “Range Rover”)
 
})
public class Car{
//code goes in here
}

With Java8 repeating annotations, it gives us the flexibility to write the same thing without any container annotation

@Manufacturer(name = “BMW”)
@Manufacturer(name= “Range Rover”)
public class Car{
//code goes in here
}

Though the container annotation was not used here, the Java compiler this time around takes responsibility for wrapping the two annotations into a container.

Now lets look at how you would use Repeating annotation.

package repeatingannotations;
 
/**
 *
 * @author imac
 */
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
 
public class RepeatingAnnotations {
 
   @Retention( RetentionPolicy.RUNTIME )
    public @interface Cars {
        Manufacturer[] value() default{};
    }
 
    @Manufacturer( "Mercedes Benz")
    @Manufacturer( "Toyota")
    @Manufacturer( "BMW")
    @Manufacturer( "Range Rover")
    public interface Car { 
 
    }
 
 
    @Repeatable(value = Cars.class )
    public @interface Manufacturer {
        String value();
 
    };
 
 
 
    public static void main(String[] args) {
 
        Manufacturer[] a = Car.class.getAnnotationsByType(Manufacturer.class );
        System.out.println("Number of car manufacturers is "+ a.length );
 
        System.out.println("\n-------Printing out Car Manufacturers--------");
 
        Cars cars = Car.class.getAnnotation(Cars.class);
        for(Manufacturer car: cars.value()){
            System.out.println(car.value());
        }
 
    }
}

Output

Number of car manufacturers is 4——-Printing out Car Manufacturers——–
Mercedes Benz
Toyota
BMW
Range Rover

As you can see, the repeating annotation has to be annotated with @Repeatable annotation.

Retrieving Annotation

There are two ways of accessing them.

  1. Accessing them via their container annotation using getDeclaredAnnotation() or getAnnotation().In the code above, we used this to print out the car manufactures
  2. Accessing them via the getAnnotationsByType() or getDeclaredAnnotationsByType() which are new methods in the Reflection API. We also used this method to print out the number of manufacturers in the code above.

Take Aways.

By default, user defined annotations are not repeatable therefore they have to be annotated with @Repeatable annotation.

Hopefully you have found this quick guide useful.

We now have a series articles explaining the key features of Java 9:

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (Twitter, Facebook and Google+) or the Blog RSS.

Related Posts:

The following two tabs change content below.

Ernest Duodu

Developer at IDRSolutions
Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.
Ernest

About Ernest Duodu

Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

One thought on “Java 8 Repeating Annotation Explained in 5 minutes

  1. darku

    Keep in mind that the Manufacturer annotation must also have a @Retention(RetentionPolicy.RUNTIME) specified on it, to be able to to annotate with only 1 Manufacturer a class, and read it properly.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>