How can I resolve this method's generic type at runtime?
My method signature: static <T> T get(String key)
The method must remain static.
Like this: (Hibernate code)
public class XXXDao<T> {
private Class<T> entityClass;
private Class<T> getEntityClass() {
if (entityClass == null) {
entityClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
return entityClass;
}
...
}
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
Object, the generics really do nothing here. I'd ask why you want to do this, what's the goal?if (Prefs.get("isActive"))or for exampleint saveTime = Prefs.get("saveTime");getOrDefaultmethod and instead calculate the default value forTwithout needing a direct argument ofT.