fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.lang.reflect.*;
  7.  
  8. abstract class Foo<T> {
  9. private final Class<T> clazz;
  10.  
  11. public Foo(List<T> list) {
  12. this.clazz = (Class<T>) ((ParameterizedType) getClass()
  13. .getGenericSuperclass()).getActualTypeArguments()[0];
  14. }
  15.  
  16. public Class<T> getClazz() {
  17. return clazz;
  18. }
  19. }
  20.  
  21. /* Name of the class has to be "Main" only if the class is public. */
  22. class Ideone
  23. {
  24.  
  25. public static void main (String[] args) throws java.lang.Exception
  26. {
  27. Foo<Integer> x = new Foo<Integer>(new ArrayList<Integer>()){};
  28. System.out.printf("<T> is %s\n", x.getClazz());
  29. Foo<String> y = new Foo<String>(new ArrayList<String>()){};
  30. System.out.printf("<T> is %s\n", y.getClazz());
  31. // Erro em runtime, <T> é genérico
  32. // criaVersaoGenerica();
  33. }
  34.  
  35. public static <K> void criaVersaoGenerica() {
  36. Foo<K> k = new Foo<K>(new ArrayList<K>()){};
  37. }
  38. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
<T> is class java.lang.Integer
<T> is class java.lang.String