Skip to content

Commit 0b3d9cc

Browse files
committed
introduces TypeReference abstract class
This class permits to extract generics Type.
1 parent 68381e5 commit 0b3d9cc

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package restx.common;
2+
3+
import java.lang.reflect.ParameterizedType;
4+
import java.lang.reflect.Type;
5+
6+
/**
7+
* This abstract class is used to extract generic types.
8+
* <p>
9+
* The {@code type} attribute hold the {@link Type} of &lt;T&gt;
10+
* <p>
11+
* For example if this class is used like this:
12+
* <pre>
13+
* Type listStringType = new TypeReference&lt;List&lt;String&gt;&gt;() {}.getType();
14+
* </pre>
15+
* The {@code listStringType} will reference the type {@code List<String>}.
16+
* <p>
17+
* The idea is based on Gafter's blog post: <a href="http://gafter.blogspot.fr/2006/12/super-type-tokens.html?m=1">
18+
* http://gafter.blogspot.fr/2006/12/super-type-tokens.html?m=1</a>
19+
*
20+
*
21+
* @author apeyrard
22+
*/
23+
public abstract class TypeReference<T> {
24+
private final Type type;
25+
26+
@SuppressWarnings("unchecked")
27+
protected TypeReference() {
28+
Type superClass = getClass().getGenericSuperclass();
29+
if (superClass instanceof Class<?>) {
30+
throw new IllegalArgumentException("TypeReference must be constructed with type information.");
31+
}
32+
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
33+
}
34+
35+
public Type getType() { return type; }
36+
}
37+
38+

0 commit comments

Comments
 (0)