1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.i18nsystem.util;
35
36 import java.lang.reflect.Method;
37 import java.lang.reflect.ParameterizedType;
38 import java.lang.reflect.Type;
39 import java.lang.reflect.WildcardType;
40 import java.util.Map;
41
42
43
44
45 public class GenericsUtils {
46
47
48
49
50
51
52
53 public static Type getGenericTypeOfReturnType(Method method) {
54 final Type returnType = method.getGenericReturnType();
55
56 if (!(returnType instanceof ParameterizedType)) {
57
58 return returnType;
59 } else {
60 return getGenericParameterType((ParameterizedType) returnType);
61 }
62 }
63
64 public static Type getGenericParameterType(ParameterizedType paramType) {
65
66 if (!(paramType.getRawType() instanceof Class)) {
67 throw new IllegalStateException("Raw type of " + paramType + " is not a Class; bailing.");
68 }
69
70 final Class<?> rawType = (Class<?>) paramType.getRawType();
71 final Type[] actualTypeArguments = paramType.getActualTypeArguments();
72 final Type actualTypeArgument;
73
74 if (actualTypeArguments.length == 1) {
75 actualTypeArgument = actualTypeArguments[0];
76 } else {
77
78 if (Map.class.isAssignableFrom(rawType) && actualTypeArguments.length == 2) {
79 actualTypeArgument = actualTypeArguments[1];
80 } else {
81 throw new IllegalStateException("Don't know what to do with multiple generics on " + paramType);
82 }
83 }
84
85 if (actualTypeArgument instanceof WildcardType) {
86 final WildcardType wildcardType = ((WildcardType) actualTypeArgument);
87 if (wildcardType.getLowerBounds().length > 0) {
88 throw new IllegalStateException("Don't know what do with WildcardType which has lower bounds: " + actualTypeArgument);
89 } else if (wildcardType.getUpperBounds().length > 1) {
90 throw new IllegalStateException("Don't know what do with WildcardType which has more than one upper bound: " + actualTypeArgument);
91 } else {
92 return wildcardType.getUpperBounds()[0];
93 }
94 }
95 return actualTypeArgument;
96 }
97 }