Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating generic's parameter

Tags:

java

generics

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?

like image 752
Hao Avatar asked May 07 '12 04:05

Hao


People also ask

Can you instantiate objects using a type parameter?

Instantiating the type parameter Since the type parameter not class or, array, You cannot instantiate it. If you try to do so, a compile time error will be generated.

Can you instantiate a generic type in Java?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

Can a generic class be instantiated without specifying an actual type argument?

You can create an instance of a generic class without specifying the actual type argument. An object created in this manner is said to be of a raw type. The Object type is used for unspecified types in raw types.


1 Answers

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();
}
like image 51
Chris B Avatar answered Oct 15 '22 18:10

Chris B