Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get type parameter values using java reflection?

interface Foo<T> { ... }
class Bar implements Foo<Baz> { ... }

I've got a Bar object. How to get the value of T for it (Baz)?

So far, I only managed to get the interface and T, but I can't see a way to get its value.

Thanks in advance.

like image 672
mik01aj Avatar asked Aug 31 '10 14:08

mik01aj


People also ask

What is the use of reflection in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is type parameter in Java?

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.

How do you find the class of a generic type?

You can get around the superfluous reference by providing a generic static factory method. Something like public static <T> GenericClass<T> of(Class<T> type) {...} and then call it as such: GenericClass<String> var = GenericClass. of(String. class) .

What is generic t in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

Type type = bar.getClass().getGenericInterfaces()[0];

if (type instanceof ParameterizedType) {
    Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0];
    System.out.println(actualType);
}

Of course, in the general case, you should iterate over the array, rather than assuming it has excatly one element ([0]). With the above example, you can cast actualType to java.lang.Class. In other cases it may be different (see comment by meriton)

like image 60
Bozho Avatar answered Oct 10 '22 17:10

Bozho