Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate generic data type in class

Tags:

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.

like image 404
h4ck3d Avatar asked Aug 23 '12 14:08

h4ck3d


People also ask

Can you instantiate a generic type?

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.

How do you instantiate a generic type class in Java?

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.

How do you declare a generic type in a class explain?

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.

How do I get a class instance of generic type T?

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.


1 Answers

T newT = (T) t.getClass().newInstance() // assuming zero args constructor and you'll                                         // have to catch some reflection exceptions 
like image 161
Ransom Briggs Avatar answered Oct 04 '22 15:10

Ransom Briggs