Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Reflection: Generic field type of subclass

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?

like image 611
Rob Moffat Avatar asked Dec 29 '22 08:12

Rob Moffat


2 Answers

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
like image 81
Kirk Woll Avatar answered Jan 08 '23 02:01

Kirk Woll


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.

like image 35
Darron Avatar answered Jan 08 '23 01:01

Darron