For example, let's get the generic return types for the slice() and asMap() methods. This can be accomplished via the Method.getGenericReturnType() method as follows:
Class<Melon> clazz = Melon.class;
Method sliceMethod = clazz.getDeclaredMethod("slice");
Method asMapMethod = clazz.getDeclaredMethod("asMap", List.class);
Type sliceReturnType = sliceMethod.getGenericReturnType();
Type asMapReturnType = asMapMethod.getGenericReturnType();
Now, calling printGenerics(sliceReturnType) will output the following:
Class of type argument: class modern.challenge.Slice
Simple name of type argument: Slice
And, calling printGenerics(asMapReturnType) will output the following:
Class of type argument: class java.lang.String
Simple name of type argument: String
Class of type argument: class java.lang.Integer
Simple name of type argument: Integer
Generic parameters of methods can be obtained via Method.getGenericParameterTypes(), as follows:
Type[] asMapParamTypes = asMapMethod.getGenericParameterTypes();
Further, we call printGenerics() for each Type (each generic parameter):
for (Type paramType: asMapParamTypes) {
printGenerics(paramType);
}
Following is the output (there is a single generic parameter, List<Melon>):
Class of type argument: class modern.challenge.Melon
Simple name of type argument: Melon