Inspecting class annotations

The Melon class has a single annotation, @Fruit:

But we can fetch all of them via getAnnotations():

Class<Melon> clazz = Melon.class;
Annotation[] clazzAnnotations = clazz.getAnnotations();

The returned array printed via Arrays.toString() reveals a single result:

[@modern.challenge.Fruit(name="melon", value="delicious")]

In order to access the name and value attributes of an annotation, we can cast it as follows:

Fruit fruitAnnotation = (Fruit) clazzAnnotations[0];
System.out.println("@Fruit name: " + fruitAnnotation.name());
System.out.println("@Fruit value: " + fruitAnnotation.value());

Or we can use the getDeclaredAnnotation() method to fetch the right type directly:

Fruit fruitAnnotation = clazz.getDeclaredAnnotation(Fruit.class);
..................Content has been hidden....................

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