dimanche 21 août 2022

Get actual type parameter from instance at runtime

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) { }
    }
}




Aucun commentaire:

Enregistrer un commentaire