I am trying implement EhCache.
As my setup of CacheManger
class uses generics thus I want my cache manager instance to be generics also.
Initially I tried using array but that came to dead end as there is no generics sol for array types.
If anyone can help me understand how does generics works with list that would be great.
What i can think of at this time is putting List.class
and then type cast to concrete types. but i can very well be wrong do suggest if this approach also can be improved.
public class CacheManager<Dao extends DaoImpl,Pojo extends PozoImpl> {
Class<Dao> clazz = null;
Class<Pojo> _clazz_pojo = null;
// < I tried Pojo[] instead of List but its not posibble with generics >
Cache<String, List<Pojo>> _cache = null;
// get cacheManager singleton obj
public static CacheManager cacheManager = EhCacheInstance.ehInstance.getInstance();
public CacheManager(Class<Dao> clazz,Class<Pojo> _clazz_pojo) {
// get cache
// < How do we init List here? >
_cache = cacheManager.getCache(_clazz_pojo.getName(), String.class, ? );
// init
if(_cache == null){
_cache = cacheManager.createCache(_clazz_cargo.getName(),
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, ? , ResourcePoolsBuilder.heap(10)));
}
// assigment
this.clazz = clazz;
this._clazz_cargo = _clazz_cargo;
}
}
Thanks in advance.
It is a generic quirk. There is no clean solution. Basically, as soon as you have something similar to <T> T get(Class<T>)
you are doomed. It is impossible to do List<String> s = get(List.class)
easily.
You need to cast somewhere and suppress the warning. In your case, I would probably do something like:
public CacheManager(Class<Dao> clazz, Class<Pojo> _clazz_pojo) {
Class<List<Pojo>> valueClass = cast(List.class);
_cache = cacheManager.getCache(_clazz_pojo.getName(), String.class, valueClass);
if(_cache == null){
_cache = cacheManager.createCache(_clazz_pojo.getName(),
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, valueClass,
ResourcePoolsBuilder.heap(10)));
}
// ...
}
@SuppressWarnings("unchecked")
private <T, V> Class<V> cast(Class<T> t) {
return (Class<V>) t;
}