fork download
  1.  
  2. import java.util.*;
  3. import java.lang.reflect.*;
  4.  
  5. class Example {
  6. public static void main(String[] args) {
  7. try {
  8. // OK
  9. System.out.println(getClassE( new ArrayList<String>() {} ));
  10.  
  11. // also OK
  12. class StringList extends ArrayList<String> {}
  13. System.out.println(getClassE( new StringList() ));
  14.  
  15. // not OK
  16. System.out.println(getClassE( new ArrayList<String>() ));
  17.  
  18. } catch(Throwable e) {
  19. e.printStackTrace(System.out);
  20. }
  21. }
  22.  
  23. static <E> Class<E> getClassE(List<E> list) {
  24. Class<?> listClass = list.getClass();
  25.  
  26. Type gSuper = listClass.getGenericSuperclass();
  27. if(!(gSuper instanceof ParameterizedType))
  28.  
  29. ParameterizedType pType = (ParameterizedType)gSuper;
  30.  
  31. Type tArg = pType.getActualTypeArguments()[0];
  32. if(!(tArg instanceof Class<?>))
  33.  
  34. @SuppressWarnings("unchecked")
  35. final Class<E> classE = (Class<E>)tArg;
  36. return classE;
  37. }
  38. }
Success #stdin #stdout 0.11s 320256KB
stdin
Standard input is empty
stdout
class java.lang.String
class java.lang.String
java.lang.IllegalArgumentException
	at Example.getClassE(Main.java:34)
	at Example.main(Main.java:16)