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?
I was just pointed to this solution:
This works if
A
is given a concrete type by a subclass: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.
public class DatabaseAccessUtil {
}
i find another way to obtain the Class of the generic object
I will elaborate on Christoph's solution.
Here is the ClassGetter abstract class:
Here is a static method which uses the above class to find a generic class' type:
As an example of it's usage, you could make this method:
And then use it like this:
T can be resolved pretty easily using TypeTools: