161. Getting generic types of method, fields, and exceptions

Let's assume that we have the following Melon class (listed are only the parts relevant to this problem):

public class Melon<E extends Exception>
extends Fruit<String, Seed> implements Comparable<Integer> {

...
private List<Slice> slices;
...

public List<Slice> slice() throws E {
...
}

public Map<String, Integer> asMap(List<Melon> melons) {
...
}
...
}

The Melon class contains several generic types associated with different artifacts. Mainly, the generic types of super classes, interfaces, classes, methods, and fields are ParameterizedType instances. For each ParameterizedType, we need to fetch the actual type of arguments via ParameterizedType.getActualTypeArguments(). The Type[] returned by this method can be iterated to extract information about each argument, as follows:

public static void printGenerics(Type genericType) {

if (genericType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) genericType;
Type[] typeOfArguments = type.getActualTypeArguments();

for (Type typeOfArgument: typeOfArguments) {
Class classTypeOfArgument = (Class) typeOfArgument;
System.out.println("Class of type argument: "
+ classTypeOfArgument);

System.out.println("Simple name of type argument: "
+ classTypeOfArgument.getSimpleName());
}
}
}

Now, let's see how we can deal with generics of methods.

..................Content has been hidden....................

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