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 TypeVariable
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: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/class-use/TypeVariable.html
Difference to ParametrizedType
:
A TypeVariable
refers to the declaration of the type variable, a ParametrizedType
is a use of such a type.
Example:
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
}
}
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