tags:

views:

1042

answers:

1

Hi all,

I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.

Example:

public class MyGenericClass<T> {
  public void doSomething() {
    // Snip...
    // Call to a 3rd party lib
    T bean = (T)someObject.create(T.class);
    // Snip...
  }
}

Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.

My question is: does someone know a good alternative or workaround for this?

+5  A: 

Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :

public class MyGenericClass<T> {

    private final Class<T> clazz;

    public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
        return new MyGenericClass<U>(clazz);
    }

    protected MyGenericClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void doSomething() {
        T instance = clazz.newInstance();
    }
}

It's ugly, but it works.

Nicolas
It sure is ugly, but the trick with protected constructor is good enough for me. I'm using the generic class as an abstract class that serves as the base 5 to 10 concrete classes. Thanks!
Jaap Coomans