Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics why can't I instantiate a genericized type [duplicate]

I was writing something using generics and to my surprise I found that this doesn't work:

class foo<T>{

 T innerT = new T();

}

So can't I instantiate the genericized type? Aren't there any ways to do this?

like image 233
gotch4 Avatar asked Jan 22 '10 09:01

gotch4


People also ask

Can you instantiate a generic type in Java?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

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.

Can generics take multiple type parameters?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

Can a generic class be instantiated without specifying an actual type argument?

You can create an instance of a generic class without specifying the actual type argument. An object created in this manner is said to be of a raw type. The Object type is used for unspecified types in raw types.


2 Answers

At the runtime JVM doesn't know what T is so it can't create new object of type T. Types are erased during compilation.

like image 67
Marcin Avatar answered Oct 21 '22 00:10

Marcin


Yeah, it's pretty damn annoying.

The work around I use is to force the client to pass the class in when constructing a new foo<T> - i.e.

public foo(Class<T> myClass)

Then you can use myClass.newInstance() instead.

like image 21
cyborg Avatar answered Oct 20 '22 22:10

cyborg