6

I'm learning Java's generic, I snag into some problem instantiating the type received from generic parameters (this is possible in C# though)

class Person { 
    public static <T> T say() {
        return new T; // this has error
    }
}

I tried this: generics in Java - instantiating T

public static <T> T say(Class<?> t) {
    return t.newInstance();
}

Error:

incompatible types
found   : capture#426 of ?
        required: T

That doesn't work. The following looks ok, but it entails instantiating some class, cannot be used on static method: Instantiating generics type in java

public class Abc<T>
 {

    public T getInstanceOfT(Class<T> aClass)
    {
       return aClass.newInstance();
    }      

} 

Is this the type erasure Java folks are saying? Is this the limitation of type erasure?

What's the work-around to this problem?

Community
  • 1
  • 1
Hao
  • 8,047
  • 18
  • 63
  • 92

1 Answers1

8

You were very close. You need to replace Class<?> (which means "a class of any type") with Class<T> (which means "a class of type T"):

public static <T> T say(Class<T> t) throws IllegalAccessException, InstantiationException {
    return t.newInstance();
}
Chris B
  • 9,149
  • 4
  • 32
  • 38
  • +1 and accepted, not as elegant as C# though (not your fault ;-) ). Btw, is this what they called type erasure, that's why it cannot instantiate a T directly? – Hao May 07 '12 at 04:26
  • 1
    @Hao: exactly: the actual type of T is not available at runtime, that's why you need to pass in a Class object to make it explicit. – Joachim Sauer May 07 '12 at 05:02