0

Suppose I have a Java class hierarchy defined as follow:

interface Bar<T> {}

class Foo<A,B> implements Bar<B> {}

How can I programmatically assess (using reflection) that the type parameter of Bar in Foo is the second of foo's parameters and not the first (B instead of A)?

I've tried using TypeVariable#getName() in order to compare the names, but when I apply getGenericInterfaces() to Foo<A,B> I get Bar<T> and not Bar<B>

Solution (thanks to @LouisWasserman): use Foo.class.getGeenricInterfaces()[0].getActualTypeParameters() returns the correct TypeVariable (B instead of T, in the previous example)

1 Answers1

0

well using TypeVariable#getName() return the type as it appears in the source code in your case it's normal to get Bar<T>. TypeVariable Doc

Using reflection in generic Classes can't help, because of Type Erasure. Erasure of Generic Types

I've the same issue in some personal projects, I tried to change the design of my class, have a look at the example below:

Instead of this:

public class Mapper<T> {

   public Mapper(){
   }
}

I used this:

public class Mapper {
   private Class<?> entityClazz;
   public Mapper(Class<?> entity){
       this.entityClazz = entity
       //Here I've donne all reflection issues i want ! 
   }
}

You can use Class#isAssignableFrom() Doc to test assignability between Class Objects.
I hope this helps, good luck !

user3728064
  • 158
  • 1
  • 11