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!

3
  • 1
    I think you mean it throws a ClassCastError which is very different to a SEG fault. Commented Jun 19, 2013 at 20:29
  • @Peter Lawrey: Yes, I was just using a common programming venacular (hence the quotation marks). Commented Jun 19, 2013 at 20:52
  • BTW You can get SEG faults in the JVM, but only with a very low level crash. Commented Jun 19, 2013 at 20:53

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

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!
Enums/EnumSets are interesting because they're one of the few java standard classes that run into this problem.
@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.
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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.