I have an immutable class , with the following layout ,
public final class A <T> { private ArrayList<T> myList; private A(){ myList = new ArrayList<T>(); } public A<T> addData(T t){ A newOb = // make a new list and instantiate using overloaded constructor T newT = new T(); ***********ERROR HERE************* newOb.myList.add(newT); return newOb; } ......... }
The error that I get here is cannot instantiate type T
. Now , I think this is related to maybe type erasure
in Java.
How can I overcome this ? I want to add a new copy of the argument that is being passed to addData into my list.
A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
Java Language Generics Instantiating a generic typepublic <T> void genericMethod() { T t = new T(); // Can not instantiate the type T. } The type T is erased. Since, at runtime, the JVM does not know what T originally was, it does not know which constructor to call.
The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
T newT = (T) t.getClass().newInstance() // assuming zero args constructor and you'll // have to catch some reflection exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With