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?
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 :
It’s ugly, but it works.