views:

173

answers:

5

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?

+9  A: 

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.

Marcin
+1. Type erasure and what Generics *really* means in Java is a must.
Joe
Furthermore, T may be an interface or an abstract class.
Jerome
Or an enum, or just an ordinary concrete class with no accessible no-args constructor.
Tom Hawtin - tackline
A: 

This is a limitation in the way java implemented generics. To allow compatibility of code using generics with legacy code before generics where added to the language, generics were implemented using type erasure. This causes a lot of confusion to people who come from langauges such as C++ and expect generic's to work in the same way.

To read more on the implications of this here is a good link

hhafez
In fact I'm a bloody C++ programmer and I always get involved in projects with this f...g Java language...
gotch4
bloody indeed...
Adriaan Koster
A: 

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.

cyborg
can't be less arsed... thanks man didn't think about this :D
gotch4
This answer doesn't explain why. You should understand why it does this before working round it.
Joe
And T can be abstract class or interface, in which case the solution is absolutely not useful.
nanda
Other answers have explained the reason for type erasure quite well. I am happy to share to the rep without basically copying what others have said.
cyborg
+4  A: 

I would always prefer a creational pattern (factory, prototype, ...). Especially

public foo(class<T> myClass)

Then you can use myClass.newInstance() instead.

is a bad solution, because T may have no empty constructor.

Zappi
A: 

Workaround

You can use the template type of a class if you subtype it. See my answer to another question.

tangens