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?
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With