Inspecting annotations of the thrown exceptions

For inspecting the annotations of the thrown exceptions, we need to call the getAnnotatedExceptionTypes() method:

This method returns the thrown exceptions types included those that are annotated:

Class<Melon> clazz = Melon.class;
Method methodEat = clazz.getDeclaredMethod("eat");
AnnotatedType[] exceptionsTypes
= methodEat.getAnnotatedExceptionTypes();

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

[@modern.challenge.Runtime() java.lang.IllegalStateException]

Extracting the first exception type can be accomplished as follows:

// class java.lang.IllegalStateException
System.out.println("First exception type: "
+ exceptionsTypes[0].getType());

Extracting the annotations of the first exception type can be done as follows:

// [@modern.challenge.Runtime()]
System.out.println("Annotations of the first exception type: "
+ Arrays.toString(exceptionsTypes[0].getAnnotations()));
..................Content has been hidden....................

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