Question

I have a class like this, and want to get the Class as showed by example (which doesn't works) in return of method getClazz. Is it possible?

public abstract class SuperTestClass<E> {

    public Class<?> getClazz() {
        return E.getClass();
    }
}
Was it helpful?

Solution

You can't unless you have it as a member field of the class. Due to type-erasure, the generic type is not available at runtime. Something like this:

public class SuperTestClass<E> {

  private final Class<E> genericClass;

  public SuperTestClass(Class<E> genericClass) {
    this.genericClass = genericClass;
  }

  // Changed return type
  public Class<E> getClassType() {
    return this.genericClass;
  }
}


// Subclass
public class TestClass extends SuperTestClass<Connection> {

    public TestClass() {
        super(Connection.class);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top