Skip to content

Instantly share code, notes, and snippets.

@stijnvanbael
Created July 10, 2013 11:52
Show Gist options
  • Save stijnvanbael/5965661 to your computer and use it in GitHub Desktop.
Save stijnvanbael/5965661 to your computer and use it in GitHub Desktop.
TypeBuilder builds parameterized Java Class references.
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