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.
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.
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.
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) .
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.
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)
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