fork download
  1. class Example<E> {
  2. public static void main(String[] args) {
  3. try {
  4. Example<String> e = new Example<String>();
  5.  
  6. // type is actually Object.class!
  7. Class<String> type = e.getGenericType();
  8. System.out.println("type is " + type.getName());
  9.  
  10. // throws ClassCastException
  11. String s = type.newInstance();
  12.  
  13. } catch(Throwable e) {
  14. e.printStackTrace(System.out);
  15. }
  16. }
  17.  
  18. Class<E> getGenericType() {
  19. return Example.<E>getClazz();
  20. }
  21.  
  22. static <T> Class<T> getClazz(T... param) {
  23. return (Class<T>) param.getClass().getComponentType();
  24. }
  25. }
Success #stdin #stdout 0.1s 321280KB
stdin
Standard input is empty
stdout
type is java.lang.Object
java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
	at Example.main(Main.java:11)