Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance of generic type in Java?

Tags:

java

generics

Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:

class SomeContainer<E> {     E createContents()     {         return what???     } } 

EDIT: It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.

I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.

like image 433
David Citron Avatar asked Sep 16 '08 18:09

David Citron


People also ask

How do you create an instance of a generic class in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.

Can you create instances of generic type parameters?

Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters.

How do I find the instance of a generic type?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the Java Tutorial for more details. A popular solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.


1 Answers

You are correct. You can't do new E(). But you can change it to

private static class SomeContainer<E> {     E createContents(Class<E> clazz) {         return clazz.newInstance();     } } 

It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.

like image 113
Justin Rudd Avatar answered Oct 05 '22 19:10

Justin Rudd