Hao
Hao

Reputation: 8115

Instantiating generic's parameter

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?

Upvotes: 6

Views: 258

Answers (1)

Chris B
Chris B

Reputation: 9259

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();
}

Upvotes: 8

Related Questions