NinjaBoy2014 NinjaBoy2014 - 5 months ago 33
Java Question

What represents reflection TypeVariable interface

I'm trying to read and understand the different interfaces and classes used by java reflection mechanism, but I didn't understand what really represent the instances of classes implementing the

interface ?

And also the following quotation from official documentation is really ambiguous :

If a type variable t is referenced by a type (i.e, class, interface or annotation type) T, and T is declared by the nth enclosing class of T (see JLS 8.1.2), then the creation of t requires the resolution (see JVMS 5) of the ith enclosing class of T, for i = 0 to n, inclusive. Creating a type variable must not cause the creation of its bounds.

Can anyone give me a small example explaining clearly what the meaning of the above paragraph?

Thanks in advance.


It represents the type variable for a method, constructor or type declaration, i.e. T in the following code snippet

public static <T> void f(){}

class A<T> {}

interface I<T> {}

class B {
    <T>B() {

Note that this is different from a type use, e.g. Integer is not a type variable in the following code snippet:

List<Integer> list = Arrays.<Integer>asList(null);

Uses of a type variable are not represented by this:

public static <T> void h(T t) {}
                     Not a TypeVariable

Here's the list of uses of the class in the standard API:

Difference to ParametrizedType:

A TypeVariable refers to the declaration of the type variable, a ParametrizedType is a use of such a type.


public class ReflectTest {

    public Collection<String> c;

    public static void main(String[] args) throws NoSuchFieldException {
        System.out.println(Collection.class.getTypeParameters()[0]); // E
        System.out.println(Collection.class.getTypeParameters()[0] instanceof TypeVariable); // true
        System.out.println(Collection.class.getTypeParameters()[0] instanceof ParameterizedType); // false
        Field field = ReflectTest.class.getField("c");
        System.out.println(field.getGenericType()); // java.util.Collection<java.lang.String>
        System.out.println(field.getGenericType() instanceof TypeVariable); // false
        System.out.println(field.getGenericType() instanceof ParameterizedType); // true