I have a class with a generic type and I want to get the class of the generic type.
I found a solution with the following code but when I use ProGuard for obfuscation, my app stops working.
Is there an other way of doing this?
public class comImplement<T> {
private T _impl = null;
public comImplement() {}
public T getImplement() {
if (_impl == null) {
ParameterizedType superClass =
(ParameterizedType) getClass().getGenericSuperclass();
Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
try {
_impl = type.newInstance();
} catch (Exception e) {
}
}
return _impl;
}
}
You can not get the type of superclass unless it’s parametrized with another generic class, e.g – List or something like that. Due to reification type parameters will be lost after compilation. You may want to solve the problem with passing instance of class you’re about to create, to method “getImplement, like below:
another problem which might raise with your code – is race condition in case if the object is shared between several threads.