Given two classes like this:
class Example1<A,B> {
public Map<A,B> someMap = new HashMap<A,B>();
}
class Example2 extends Example1<URL, URL> {
}
Is there any way using reflection that I can determine the component types of the Map for Example2?
I know I can do:
ParameterizedType t = (ParameterizedType) Example2.class.getFields()[0].getGenericType();
But from there, I can't seem to figure out that the two components are URLs.
Does anyone have any ideas?
Darron is not completely correct. The following will print out what you want:
ParameterizedType superClass = (ParameterizedType) Example2.class.getGenericSuperclass();
System.out.println(superClass.getActualTypeArguments()[0]);
System.out.println(superClass.getActualTypeArguments()[1]);
Prints out:
class java.net.URL
class java.net.URL
Because Java generics are implemented via "erasure", this information is not available at runtime through reflection.
EDIT: it seems I missed some detail of the question. In this sort of specialized case the type information is available.
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