0

basically what I'm trying to do is allocate a parametrized type from a generic function:

public < T > T wishful_thinking(  )
{
    return new T( );
}

Casting doesn't work either, due to "object slicing" (that is, it compiles, but "segfaults"):

public < T > T wishful_thinking(  )
{
    return ( T )new Object( );
}

So...is there any workaround for this (perhaps using reflection or some such)?

Thanks!

SeaBass
  • 121
  • 10

2 Answers2

5

You can't. The solution is to pass a Class object in your method and use reflection to create an instance.

Example without any exception handling:

public <T> T wishful_thinking(Class<T> clazz)
{
    return clazz.newInstance();
}
LaurentG
  • 9,745
  • 8
  • 44
  • 61
  • Grrr...there has got to be some way to do this. It's funny really, Java Generics is a compile-time (as opposed to run-time) facility, and yet it doesn't even account for such a basic operation! – SeaBass Jun 19 '13 at 20:30
  • Enums/EnumSets are interesting because they're one of the few java standard classes that run into this problem. – Nuoji Jun 19 '13 at 20:31
  • 1
    @SeaBass If the caller can't allocate it, then there is no way a function lower in the call hierarchy could possibly manage it. For instance, if the caller passed an abstract class or interface. – AJMansfield Jun 19 '13 at 20:33
3

Generics are not reified in Java. Thus, you can't have something like new T(), since T is erased.

The only way to get an object is using Class representation :

public <T> T wishful_thinking( Class<T> classToInstanciate ) throws ...
{
   return classToInstanciate.newInstance();
}
Guillaume Darmont
  • 4,702
  • 1
  • 19
  • 34