Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.util.ArrayList;
- import java.util.List;
- public abstract class TypeReference<T> {
- private final Type type;
- private volatile Constructor<?> constructor;
- public TypeReference() {
- Type superclass = getClass().getGenericSuperclass();
- if (superclass instanceof Class) {
- throw new RuntimeException("Missing type parameter");
- }
- this.type = ((ParameterizedType)superclass).getActualTypeArguments()[0];
- }
- public T newInstance() throws NoSuchMethodException,
- IllegalAccessException, InvocationTargetException, InstantiationException {
- if (constructor == null) {
- Class<?> rawType = type instanceof Class<?>
- ? (Class<?>) type
- : (Class<?>) ((ParameterizedType)type).getRawType();
- constructor = rawType.getConstructor();
- }
- return (T)constructor.newInstance();
- }
- public Type getType() {
- return this.type;
- }
- public static void main(String[] args) throws Exception {
- List<String> l1 = new TypeReference<ArrayList<String>>() {}.newInstance();
- List l2 = new TypeReference<ArrayList>() {}.newInstance();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement