Śhāhēēd
Śhāhēēd

Reputation: 1882

How to get parameterized type

Please follow the code snippet

public class A<T> {

private T genericInstance() {
    T target = null;
    try {
        Class<T> clazz = getGenericClass();
        target = clazz.newInstance();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return target;
}

@SuppressWarnings("unchecked")
private Class<T> getGenericClass() {
    ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
    Type[] types = type.getActualTypeArguments();
    return (Class<T>) types[0];
}

}

while I execute the code getGenericClass() its return the the Generic Super class but my requirement is to get class of T and want to instantiate it dynamically.

Upvotes: 3

Views: 3714

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

You need an instance of T (or to pass in the class) because of type-erasure. Java generics provide compile time type-checking only, at run-time the generic is of type Object. In practice, this is not difficult, because you know the type T at compile-time; for example, A<Integer> a = new A<Integer>(Integer.class); // Integer.class matches the other Integer(s)

public class A<T> {
  private Class<T> clazz;

  public A(Class<T> clazz) {
    this.clazz = clazz;
  }

  public T genericInstance() {
    T target = null;
    try {
      // Class<T> clazz = getGenericClass();
      target = clazz.newInstance();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return target;
  }
}

Upvotes: 3

Related Questions