NinjaBoy2014 NinjaBoy2014 - 5 months ago 17
Java Question

Creation of TypeVariable instances

The official documentation of

is really confusing, firstly it specifies that :

A type variable is created the first time it is needed by a reflective method


Repeated creation of a type variable has no effect

So what I understand is that there's only one instance of
representing a type variable at run-time, for example :

class A<T> {}

We will have one instance of
Type Variable
that represent
at run-time.

But the documentation adds :

Multiple objects may be instantiated at run-time to represent a given type variable. Even though a type variable is created only once, this does not imply any requirement to cache instances representing the type variable. However, all instances representing a type variable must be equal() to each other

From the above quotation I understand that there are two kinds of instantiation :

  1. Creation of type variable (Which i don't understand)

  2. Instantiation of multiple instances representing type variable

Can anyone please explain what the difference between them ?


Consider the following class:

class Ideone<T> {
  List<T> getList() { ... }

It is saying that the type variables representing the <T> on the class and the <T> on the method aren't necessarily the same instance:

TypeVariable onClass = Ideone.class.getTypeParameters()[0];
TypeVariable onMethod = Ideone.class.getDeclaredMethod("getList").getReturnType().getTypeParameters()[0];

System.out.println(onClass == onMethod);

Prints false, even though they're representing the same type variable.

Ideone demo