I'm trying to get a class from a generic whose type was defined in the parent class and do it like this:
public class Generic<T> extends Generic1<T> { Object[] objects; int index; public void f1(int size) { this.objects = new Object[size]; Class<T> t = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; try { T value = t.newInstance(); System.out.printf("string " + value); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } System.out.println(t.toString()); } public static void main(String[] args) { Generic<String> g = new Generic<>(); g.f1(3); } } class Generic1<String> { } And it seems to me that everything should work. But it falls with the following exception:
Java.lang.ClassCastException in thread "main" Generic.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodA.ph.e.ph.e.off.eferaImpl.java:62 at sun.reflect.DelegatingMethodA.ph.e. .lang.reflect.Method.invoke (Method.java:498) at com.intellij.rt.execution.application.AppMain.main (AppMain.java:147)
Help me figure out what I'm missing here? And why ClassCastException ? Help me fix the code to working condition.