fork(1) download
  1. import java.util.*;
  2. import java.lang.reflect.*;
  3.  
  4. class Example {
  5. public static void main(String[] args) {
  6. {
  7. ArrayList<Long> al = new ArrayList<Long>();
  8. printTypeInfo("ArrayList<Long> al = new ArrayList<Long>();", al);
  9. }
  10. {
  11. ArrayList<Long> al = new ArrayList<Long>() {};
  12. printTypeInfo("ArrayList<Long> al = new ArrayList<Long>() {};", al);
  13. }
  14. }
  15.  
  16. private static void printTypeInfo(String declaration, ArrayList<Long> al) {
  17. System.out.println(declaration);
  18.  
  19. printTypeInfo("al.getClass()",
  20. al.getClass());
  21. printTypeInfo("al.getClass().getGenericSuperclass()",
  22. al.getClass().getGenericSuperclass());
  23.  
  24. Type actualTypeArgument =
  25. ((ParameterizedType)
  26. al.getClass()
  27. .getGenericSuperclass())
  28. .getActualTypeArguments() [0];
  29. printTypeInfo("al.getClass().getGenericSuperclass().getActualTypeArguments()[0]",
  30. actualTypeArgument);
  31. }
  32.  
  33. private static void printTypeInfo(String expr, Type t) {
  34. System.out.printf(" %s%n", expr);
  35. System.out.printf(" is an instance of '%s'%n", t.getClass().getSimpleName());
  36. System.out.printf(" representing the type '%s'", t.getTypeName());
  37.  
  38. if (t instanceof Class<?> && ((Class<?>) t).isAnonymousClass()) {
  39. System.out.printf(" (anonymous subclass of %s)%n", ((Class<?>) t).getSuperclass().getName());
  40. } else {
  41. System.out.println();
  42. }
  43. }
  44. }
Success #stdin #stdout 0.09s 27916KB
stdin
Standard input is empty
stdout
ArrayList<Long> al = new ArrayList<Long>();
  al.getClass()
    is an instance of 'Class'
    representing the type 'java.util.ArrayList'
  al.getClass().getGenericSuperclass()
    is an instance of 'ParameterizedTypeImpl'
    representing the type 'java.util.AbstractList<E>'
  al.getClass().getGenericSuperclass().getActualTypeArguments()[0]
    is an instance of 'TypeVariableImpl'
    representing the type 'E'
ArrayList<Long> al = new ArrayList<Long>() {};
  al.getClass()
    is an instance of 'Class'
    representing the type 'Example$1' (anonymous subclass of java.util.ArrayList)
  al.getClass().getGenericSuperclass()
    is an instance of 'ParameterizedTypeImpl'
    representing the type 'java.util.ArrayList<java.lang.Long>'
  al.getClass().getGenericSuperclass().getActualTypeArguments()[0]
    is an instance of 'Class'
    representing the type 'java.lang.Long'