Search code examples
javagenericsreflectionconstructorgeneric-programming

Get Generic Type in Constructor in java


Is there a way to find generic type in constructor?

 public class geneticarg {
    public static void main(String[] args) {
    a<String> a1 = new a<String>("a");
    a<String> a2 = new a<String>(null); // gives NPE
    System.out.println(a1.getClazz());
    }
}

class a<T> {

private Class<T> clazz;
private T element;

public a(T clazz) {
this.clazz = (Class<T>) clazz.getClass();
this.element = clazz;
// what if clazz is null ?

}
//getter and setter
}

EDIT : It is not necessary that always String comes.


Solution

  • The only way to avoid type erasure in your case is to use generic superclass. You need to subclass your generic type and then you can access parametrized type, it is available via reflection API:

    public abstract class a<T> {
    
        private Class<T> clazz;
        private T element;
    
        public a(T obj) {
            ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
            this.clazz = (Class<T>) type.getActualTypeArguments()[0];
            this.element = obj;
        }
    }
    
    class StringA extends a<String> {
        public StringA(String obj) {
            super(obj);
        }
    }