Suppose I have a Java class parameterized on that contains a private T _member. I want to write a default constructor (no arguments), that somehow initializes my T _member to some known, type T specific value (like -1 for Integer, Float.MAX_VALUE for Float...). Is that possible? I tried new T(), but the compiler doesn't like that. Or do I do nothing, and the default constructor is guaranteed to be called for me?
If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.
A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.
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.
Because of type erasure, at runtime "there is no T".
The way around it is to pass an instance of Class<T>
into the constructor, like this:
public class MyClass<T> {
T _member;
public MyClass(Class<T> clazz) {
_member = clazz.newInstance(); // catch or throw exceptions etc
}
}
BTW, this is a very common code pattern to solve the issue of "doing something with T"
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