PageRenderTime 39ms CodeModel.GetById 31ms app.highlight 5ms RepoModel.GetById 2ms app.codeStats 0ms

/sitebricks-converter/src/main/java/com/google/sitebricks/conversion/generics/TypeToken.java

http://github.com/dhanji/sitebricks
Java | 97 lines | 58 code | 12 blank | 27 comment | 4 complexity | 43bab13e5482bb9d11105528c8ebb89a MD5 | raw file
 1/*
 2 * Copied from Gentyref project http://code.google.com/p/gentyref/
 3 * Reformatted and moved to fit package structure
 4 */
 5
 6package com.google.sitebricks.conversion.generics;
 7
 8import java.lang.reflect.ParameterizedType;
 9import java.lang.reflect.Type;
10
11/**
12 * Wrapper around {@link Type}.
13 *
14 * You can use this to create instances of Type for a type known at compile
15 * time.
16 *
17 * For example, to get the Type that represents List<String>:
18 * <code>Type listOfString = new TypeToken&lt;List&lt;String&gt;&gt;(){}.getType();</code>
19 *
20 * @author Wouter Coekaerts <wouter@coekaerts.be>
21 *
22 * @param <T>
23 *            The type represented by this TypeToken.
24 */
25public abstract class TypeToken<T>
26{
27	private final Type type;
28
29	/**
30	 * Constructs a type token.
31	 */
32	protected TypeToken()
33	{
34		this.type = extractType();
35	}
36
37	private TypeToken(Type type)
38	{
39		this.type = type;
40	}
41
42	public Type getType()
43	{
44		return type;
45	}
46
47	private Type extractType()
48	{
49		Type t = getClass().getGenericSuperclass();
50		if (!(t instanceof ParameterizedType))
51		{
52			throw new RuntimeException("Invalid TypeToken; must specify type parameters");
53		}
54		ParameterizedType pt = (ParameterizedType) t;
55		if (pt.getRawType() != TypeToken.class)
56		{
57			throw new RuntimeException("Invalid TypeToken; must directly extend TypeToken");
58		}
59		return pt.getActualTypeArguments()[0];
60	}
61
62	/**
63	 * Gets type token for the given {@code Class} instance.
64	 */
65	public static <T> TypeToken<T> get(Class<T> type)
66	{
67		return new SimpleTypeToken<T>(type);
68	}
69
70	/**
71	 * Gets type token for the given {@code Type} instance.
72	 */
73	public static TypeToken<?> get(Type type)
74	{
75		return new SimpleTypeToken<Object>(type);
76	}
77
78	private static class SimpleTypeToken<T> extends TypeToken<T>
79	{
80		public SimpleTypeToken(Type type)
81		{
82			super(type);
83		}
84	}
85
86	@Override
87	public boolean equals(Object obj)
88	{
89		return (obj instanceof TypeToken<?>) && type.equals(((TypeToken<?>) obj).type);
90	}
91
92	@Override
93	public int hashCode()
94	{
95		return type.hashCode();
96	}
97}