Advertisement
Guest User

Untitled

a guest
Aug 28th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import java.lang.reflect.Constructor;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.ParameterizedType;
  4. import java.lang.reflect.Type;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. public abstract class TypeReference<T> {
  9.  
  10. private final Type type;
  11. private volatile Constructor<?> constructor;
  12.  
  13. public TypeReference() {
  14. Type superclass = getClass().getGenericSuperclass();
  15. if (superclass instanceof Class) {
  16. throw new RuntimeException("Missing type parameter");
  17. }
  18. this.type = ((ParameterizedType)superclass).getActualTypeArguments()[0];
  19. }
  20.  
  21. public T newInstance() throws NoSuchMethodException,
  22. IllegalAccessException, InvocationTargetException, InstantiationException {
  23. if (constructor == null) {
  24. Class<?> rawType = type instanceof Class<?>
  25. ? (Class<?>) type
  26. : (Class<?>) ((ParameterizedType)type).getRawType();
  27. constructor = rawType.getConstructor();
  28. }
  29.  
  30. return (T)constructor.newInstance();
  31. }
  32.  
  33. public Type getType() {
  34. return this.type;
  35. }
  36.  
  37. public static void main(String[] args) throws Exception {
  38. List<String> l1 = new TypeReference<ArrayList<String>>() {}.newInstance();
  39. List l2 = new TypeReference<ArrayList>() {}.newInstance();
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement