I was writing something using generics and to my surprise I found that this doesn't work:
class foo<T>{
T innerT = new T();
}
So can't I instantiate the genericized type? Aren't there any ways to do this?
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.
A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
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.
At the runtime JVM doesn't know what T is so it can't create new object of type T. Types are erased during compilation.
Yeah, it's pretty damn annoying.
The work around I use is to force the client to pass the class in when constructing a new foo<T>
- i.e.
public foo(Class<T> myClass)
Then you can use myClass.newInstance()
instead.
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