Created
July 10, 2013 11:52
-
-
Save stijnvanbael/5965661 to your computer and use it in GitHub Desktop.
TypeBuilder builds parameterized Java Class references.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.ParameterizedType; | |
import java.lang.reflect.Type; | |
/** | |
* <p>TypeBuilder builds parameterized {@code Class<?>} references. Example:</p> | |
* <pre> | |
* {@code | |
* Class<List<String>> type = new TypeBuilder<List<String>>() { }.build(); | |
* } | |
* </pre> | |
*/ | |
public abstract class TypeBuilder<T> { | |
public Class<T> build() { | |
Type superclass = getClass().getGenericSuperclass(); | |
if (superclass instanceof Class) { | |
throw new RuntimeException("Missing type parameter."); | |
} | |
ParameterizedType parameterized = (ParameterizedType) superclass; | |
return convert(parameterized.getActualTypeArguments()[0]); | |
} | |
@SuppressWarnings("unchecked") | |
private Class<T> convert(Type type) { | |
if (type instanceof Class) { | |
return (Class<T>) type; | |
} else if (type instanceof ParameterizedType) { | |
ParameterizedType parameterizedType = (ParameterizedType) type; | |
Type rawType = parameterizedType.getRawType(); | |
return (Class<T>) rawType; | |
} else { | |
return null; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment