My question is about type variables used in generic classes and methods.
Why can't we do something like this T = new T();
or in other words, why can't we construct an object of the type variable ?
I know that generic information is erased during compilation, and everything is converted to
Object, so why doesn't the compiler assume that T
is an object and let us construct it ?
The generic value variable is a type of variable with a wide range that can store any kind of data, including text, numbers, dates and arrays, and is particular to UiPath Studio. Generic value variables are automatically converted to other types, in order to perform certain actions.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section.
Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
The problem is that at runtime the JVM does not know which class the T
actually stands for (that information is not retained at runtime, that's what "type erasure" means). Therefore the JVM just sees that you want to construct a new T
, but has no idea which constructor to actually invoke - hence it's not allowed.
There are workarounds, but it will not work as you propose.
why doesn't the compiler assume that T is an object and let us construct it ??
Well, of course the runtime could just construct an instance of java.lang.Object
for you, but that would not really help, as you really wanted a T
.
In addition to sleske's answer; if you need to create objects of T inside your generic class, the solution is to pass a Class<T>
reference as argument to either the constructor or the method that needs to create new objects and use that class to create new instances.
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