How to Add Type and Repeating Annotations to Code in Java 8

See Java: Tips and Tricks for similar articles.

Java developers typically need to store objects of a given type in a data structure such as an array. An efficient technique to achieve this goal is available in Java 8 by adding type and repeating annotations to your Java application. The type annotation permits the developer to use an annotation in place of a class reference. The repeating annotation, @Repeatable, calls out an annotated class that serves as the container for the objects. To understand how to add type and repeating annotations to Java 8 code, follow these 10 steps.

  1. Open your text editor and create the Java program that will define the class that we wish to create, in this case a musical instrument. Type in the following Java statements:
    
    import java.lang.annotation.*;
    @Repeatable(value=MusicalInstruments.class)
    public @interface MusicalInstrument {
    	String  name() default "";
    	double price() default 0.0;
    }
    
    The class is not a class at all! Instead, you have coded an interface that defines the annotation methods that each have default implementations. Notice the @Repeatable annotation indicates repeating instances of musical instrument can be stored in a collection (e.g., an array) returned by the value method in the referenced interface (in this case MusicalInstruments that you will code in a later step).
  2. Save your file as MusicalInstrument.java.
  3. Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter: Compile program with Musical Instrument annotation
  4. Now you will create the interface that was referenced in the MusicalInstrument interface by means of the @Repeatable annotation. In your text editor, create the Java interface named MusicalInstruments. Type in the following Java statements:
    
    import java.lang.annotation.*;
    @Retention( RetentionPolicy.RUNTIME )
    public @interface MusicalInstruments {
    	MusicalInstrument[] value();
    }
    
    Notice that the interface defines one method, value, that returns an array of type MusicalInstrument. Recall that this method name was specified in the MusicalInstrument interface when the @Repeatable annotation was referenced. The retention policy specified by the @Retention annotation indicates that the array is to be retained at runtime.
  5. Save your file as MusicalInstruments.java.
  6. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter: Compile program with Musical Instrument annotations
  7. You are now ready to create your tester program. In your text editor, type in the following Java statements:
    
    import java.lang.annotation.*;
    @MusicalInstrument(name="Piano", price=1200.00)
    @MusicalInstrument(name="Trumpet", price=200)
    @MusicalInstrument(name="Clarinet", price=450)
    public class AddTypeAndRepeatingAnnotations {
    	public static void main (String args[]) {
    		// Retrieve annotations by type, i.e., MusicalInstrument
    		// Returns an array
    		MusicalInstrument[] annotations=AddTypeAndRepeatingAnnotations.class.getAnnotationsByType(MusicalInstrument.class);
    		for (MusicalInstrument mI : annotations) {
    			System.out.println(mI);
    		}
    		// Retrieve annotations using container class, i.e., MusicalInstruments
    		// Returns an object of type container class
    		MusicalInstruments instruments=AddTypeAndRepeatingAnnotations.class.getAnnotation(MusicalInstruments.class);
    		for (MusicalInstrument mI : instruments.value()) {
    			System.out.println(mI.name() + " cost: " + mI.price());
    		}
    	}
    }
    
    The @MusicalInstrument annotation is used to create each musical instrument that will be stored in the array. The name and price attributes correspond to the interface methods and provide the values returned by each method. The getAnnotationsByType method is used to display the @MusicalInstrument annotations used by this class. The classes that result from using the annotation are returned as an array. The getAnnotation method returns the result of using the @MusicalInstruments annotation. This result is a collection of musical instruments. The for loop is used to display the collection contents.
  8. Save your file as AddTypeAndRepeatingAnnotations.java.
  9. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter: Compile program to Test Musical Instrument annotation
  10. You are ready test your Java program. Type in the command to run the Java runtime launcher and hit Enter. Run program to Test Musical Instrument annotation Notice the output shows the musical instruments created by calling the annotation and the musical instruments stored in the array.

Related Articles

  1. How to Check Object Type in Java
  2. How to Create a Jar File in Java
  3. How to Compile Packages in Java
  4. How to Throw an Exception in Java
  5. How to Create an Exception Class in Java
  6. How to Use the super Keyword to Call a Base Class Constructor in Java
  7. How to Use the Comparator.comparing Method in Java 8
  8. How to Use System.in in Java
  9. How to Call an Interface Method in Java
  10. How to Add a Time Zone in the Java 8 Date/Time API
  11. How to Rethrow an Exception in Java
  12. How to Use the instanceof Operator with a Generic Class in Java
  13. How to Instantiate an Object in Java
  14. How to Filter Distinct Elements from a Collection in Java 8
  15. How to Create a Derived Class in Java
  16. How to Skip Elements with the Skip Method in Java 8
  17. How to Create a Java Bean
  18. How to Implement an Interface in Java
  19. How to Compare Two Objects with the equals Method in Java
  20. How to Set PATH from JAVA_HOME
  21. How to Prevent Race Conditions in Java 8
  22. How to Write a Block of Code in Java
  23. How to Display the Contents of a Directory in Java
  24. How to Group and Partition Collectors in Java 8
  25. How to Create a Reference to an Object in Java
  26. How to Reduce the Size of the Stream with the Limit Method in Java 8
  27. How to Write an Arithmetic Expression in Java
  28. How to Format Date and Time in the Java 8 Date/Time API
  29. How to Use Comparable and Comparator in Java
  30. How to Break a Loop in Java
  31. How to Use the this Keyword to Call Another Constructor in Java
  32. How to Write a Unit Test in Java
  33. How to Declare Variables in Java
  34. How to Override Base Class Methods with Derived Class Methods in Java
  35. How to Use Serialized Objects in Java
  36. How to Write Comments in Java
  37. How to Implement Functional Interfaces in Java 8
  38. How to Write Type Parameters with Multiple Bounds in Java
  39. How to Add Type and Repeating Annotations to Code in Java 8 (this article)
  40. How to Use Basic Generics Syntax in Java
  41. How to Map Elements Using the Map Method in Java 8
  42. How to Work with Properties in Java
  43. How to Write while and do while Loops in Java
  44. How to Use the finally Block in Java
  45. How to Write for-each Loops in Java
  46. How to Create a Method in Java
  47. How to Continue a Loop in Java
  48. How to Handle Java Files with Streams
  49. How to Create an Interface Definition in Java
  50. How Default Base Class Constructors Are Used with Inheritance