Skip to content

Instantly share code, notes, and snippets.

@praveenhm
Created February 22, 2016 19:59
Show Gist options
  • Save praveenhm/51ed502ba052f14afcf5 to your computer and use it in GitHub Desktop.
Save praveenhm/51ed502ba052f14afcf5 to your computer and use it in GitHub Desktop.

Revisions

  1. praveenhm created this gist Feb 22, 2016.
    43 changes: 43 additions & 0 deletions TypeReference.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@

    public abstract class TypeReference<T> {

    private final Type type;
    private volatile Constructor<?> constructor;

    protected TypeReference() {
    Type superclass = getClass().getGenericSuperclass();
    if (superclass instanceof Class) {
    throw new RuntimeException("Missing type parameter.");
    }
    this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
    }

    /**
    * Instantiates a new instance of {@code T} using the default, no-arg
    * constructor.
    */
    @SuppressWarnings("unchecked")
    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();
    }

    /**
    * Gets the referenced type.
    */
    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();
    }
    }