1

I'm using Spring boot and I'm doing reflection to extract classes within my package ending with "Repository" and all fields declared as MyGenericClass<T,R>. My problem is that I am unable to extract ClassA and ClassB from myField

public class ContainerRepository{
private MyGenericClass<ClassA, ClassB> myField;}

I wish to run the same code against:

public class ProcessRepository{
private MyGenericClass<ClassC, ClassD> anotherField;}

and getClassC and ClassD from anotherField

RAFJR
  • 362
  • 1
  • 7
  • 22
  • 3
    You cannot do that. Reflection retrieves the runtime type, and due to type erasure, the generic class parameters will be gone. See http://www.baeldung.com/java-type-erasure – daniu May 02 '18 at 08:18
  • 2
    Possible duplicate of [How can I determine the type of a generic field in Java?](https://stackoverflow.com/questions/1868333/how-can-i-determine-the-type-of-a-generic-field-in-java) – dfogni May 02 '18 at 09:54

1 Answers1

2

Simple answer, you can't infer generics at run time using Reflection. However, you can mark your field types easily as a instance variable(quite a hack but not sure if it helps).

public class MyGenericClass<M, N> {

    private M mType;
    private N nType;

    MyGenericClass (M m, N n){
        this.mType = m;
        this.nType = n;
    }

    public Class<?> getMType(){
        return this.mType.getClass();
    }

    public Class<?> getNType(){
        return this.nType.getClass();
    }

}

Reference below: https://stackoverflow.com/a/26088911/2931410

Karthik R
  • 5,523
  • 2
  • 18
  • 30