Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic Type Variables

Tags:

java

generics

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 ?

like image 561
Ibrahim Najjar Avatar asked Oct 26 '10 08:10

Ibrahim Najjar


People also ask

What are generic variables?

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.

What is generic type class in Java?

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.

In which way generic declares one or more type variables?

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.

What is a generic type parameter?

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.


2 Answers

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.

like image 96
sleske Avatar answered Oct 07 '22 22:10

sleske


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.

like image 36
rsp Avatar answered Oct 07 '22 22:10

rsp