Generics of exceptions

Generic types of exceptions are materialized in instances of TypeVariable or ParameterizedType. This time, the helper method for extracting and printing information about generics based on TypeVariable can be written as follows:

public static void printGenericsOfExceptions(Type genericType) {

if (genericType instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) genericType;
GenericDeclaration genericDeclaration
= typeVariable.getGenericDeclaration();

System.out.println("Generic declaration: " + genericDeclaration);

System.out.println("Bounds: ");
for (Type type: typeVariable.getBounds()) {
System.out.println(type);
}
}
}

Having this helper, we can pass to it the exceptions thrown by a method via getGenericExceptionTypes(). If an exception type is a type variable (TypeVariable) or a parameterized type (ParameterizedType), it is created. Otherwise, it is resolved:

Type[] exceptionsTypes = sliceMethod.getGenericExceptionTypes();

Further, we call the printGenerics() for each Type:

for (Type paramType: exceptionsTypes) {
printGenericsOfExceptions(paramType);
}

The output will be as follows:

Generic declaration: class modern.challenge.Melon
Bounds: class java.lang.Exception
Most probably, printing the extracted information about generics will not be useful, therefore, feel free to adapt the preceding helpers based on your needs. For example, collect the information and return it as List, Map, and so on.
..................Content has been hidden....................

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