我有以下類:如何獲取Java泛型的類對象?
public abstract class AbstractService<PersistenceClass extends IPersistence,
RequestClass, ResponseClass> {
public String processRequest(final String aRequestAsText)
{
[...]
final RequestClass request = mapper.readValue(aRequestAsText,
RequestClass);
[...]
}
}
的mapper.readValue invokation通常作爲
mapper.readValue(aRequestAsText, Request.class)
我如何可以編寫它來實現,如果類RequestClass是一個通用的?
更新1(2013年6月9日):此代碼似乎工作:
public class GenericTypeBindigsFinder implements IGenericTypeBindigsFinder {
@SuppressWarnings("rawtypes")
@Override
public List<Class> getGenericTypes(final Class aClass) {
final List<Class> result = new LinkedList<Class>();
final ParameterizedType gen = (ParameterizedType) aClass.getGenericSuperclass();
final Type [] types = gen.getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
if (types[i] instanceof Class)
{
final Class clazz = (Class)types[i];
result.add(clazz);
}
}
return result;
}
}
你可以找到相應的單元測試here。
你想要從一個泛型聲明類型參數? – Mauren
不,我想要得到'RequestClass'類的對象(某種'RequestClass.class')。 –
@DmitriPisarenko:請勿將反引號用於非代碼,請參閱[here why(http://meta.gaming.stackexchange.com/q/7437/88) –