Click here to watch in Youtube :
https://www.youtube.com/watch?v=3RzZde1ZTpE&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java Tutorial: Annotations in java | Java annotations [repeating Annotations in Java] |
import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /* * Step 1: Declare a Repeatable Annotation Type * * The annotation type must be marked with the * @Repeatable meta-annotation */ @Repeatable(value = Cars.class) @interface Manufacturer { String name(); }; /* * Step 2: Declare the Containing Annotation Type * * The containing annotation type must have a value element * with an array type. The component type of the array type * must be the repeatable annotation type. */ @Retention(RetentionPolicy.RUNTIME) @interface Cars { Manufacturer[] value() default {}; } @Manufacturer(name = "Mercedes Benz") @Manufacturer(name = "Toyota") @Manufacturer(name = "BMW") @Manufacturer(name = "Range Rover") public interface Car { }RepeatingAnnotations.java
public class RepeatingAnnotations { public static void main(String[] args) { /* * Retrieving Annotations using Reflection API * method */ Manufacturer[] manufacturerArray = Car.class .getAnnotationsByType(Manufacturer.class); System.out.println("Number of car manufacturers is " + manufacturerArray.length); for (Manufacturer manufacturer : manufacturerArray) { System.out.println(manufacturer + " , name = " + manufacturer.name()); } System.out.println("\n-------Printing out Car Manufacturers--------"); /* * Retrieving Annotations using Reflection API * method */ Cars cars = Car.class.getAnnotation(Cars.class); System.out.println(cars); manufacturerArray = cars.value(); for (Manufacturer manufacturer : manufacturerArray) { System.out.println(manufacturer + " , name = " + manufacturer.name()); } } }Output
Number of car manufacturers is 4 @Manufacturer(name=Mercedes Benz) , name = Mercedes Benz @Manufacturer(name=Toyota) , name = Toyota @Manufacturer(name=BMW) , name = BMW @Manufacturer(name=Range Rover) , name = Range Rover -------Printing out Car Manufacturers-------- @Cars(value=[@Manufacturer(name=Mercedes Benz), @Manufacturer(name=Toyota), @Manufacturer(name=BMW), @Manufacturer(name=Range Rover)]) @Manufacturer(name=Mercedes Benz) , name = Mercedes Benz @Manufacturer(name=Toyota) , name = Toyota @Manufacturer(name=BMW) , name = BMW @Manufacturer(name=Range Rover) , name = Range RoverClick the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/AnnotationDemo_Repeating_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/AnnotationDemo_Repeating_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/AnnotationDemo_Repeating_App/?at=master
See also:
No comments:
Post a Comment