1

I have instance of class with type parameter. I want to find actual type parameter, not just some generic information returned by getTypeParameters method:

public class Program {
    public static void main(String[] args) {
        ClassWithParam<Class1> instance1 = new ClassWithParam<>(new Class1());
        Class c1 = getTypeParam(instance1); // I want this to be Class1.class
    }

    private static Class getTypeParam(ClassWithParam<?> instance) {
         var typeParameters = instance.getClass().getTypeParameters();
         // nothing useful here...
    }

    private static class Class1 { }

    private static class ClassWithParam<T> {
        public ClassWithParam(T value) { }
    }
}
Zergatul
  • 1,957
  • 1
  • 18
  • 28
  • What you want is not possible, Zergatul. That's what "type erasure" means. This information is __erased__ by the compiler; once you're at the runtime level (which is where you are, when you're running the `getTypeParam` method), it's therefore _simply impossible to retrieve_. Because it has been erased. – rzwitserloot Aug 22 '22 at 02:25
  • @rzwitserloot thanks. I came from c# and it is hard to believe this is not possible in Java – Zergatul Aug 22 '22 at 08:25

0 Answers0