Reputation: 4113
I have requirement where I want to define a generic class
which implements a generic interface
.
This is my custom map interface:
public interface ICache<K, T> {
boolean containsKey(K k);
T getValue (K key);
void remove(K key);
void put(K k, T t);
}
This is the custom class implementation:
public class CustomCache<K, T> implements ICache<K, T> {
private org.infinispan.Cache<K, T> cache;
public CustomCache(org.infinispan.Cache<K, T> cache) {
this.cache = cache;
}
@Override
public boolean containsKey(K k) {
return cache.containsKey(k);
}
@Override
public T getValue(K key) {
return cache.get(key);
}
@Override
public void remove(K key) {
cache.remove(key);
}
@Override
public void put(K k, T t) {
cache.put(k, t);
}
}
But when I try to construct a Cache, I get warnings like "Cache is a raw type. References to generic type Cache should be parameterized"...
A sample method to create a custom map.
public ICache<?, ?> lookupCache(String cacheName) {
ICache<?, ?> cache = null;
Cache<?, ?> jCache = new DefaultCacheManager().getCache();
cache = new CustomCache(jCache);
return cache;
}
One way to avoid this is simply use, @SuppressWarnings, but can I fix the same using generic.
Using the <> operator though fixes this, but I need to make it 1.6 compatible too.
Upvotes: 2
Views: 890
Reputation: 38132
Without trying, I think you can solve situations like this using a generic helper method:
private <K, T> ICache<K, T> createCache)(org.infinispan.Cache<K, T> cache){
return new CustomCache<K, T>(cache);
}
Upvotes: 1
Reputation: 9705
The warning pretty much sums it up: your class Cache
is a generic type, meaning it takes type parameters, but your reference to the Cache
object called jCache
doesn't have such type parameters. You should not only supply them in the declaration, but also in the initialization, like so:
cache = new CustomCache<Object, Object>(jCache);
It basically says that you have an object of class CustomCache
but you don't know the K
nor the T
type (yet). All you can say at this point is you'll put only Object
s in it.
Upvotes: 1
Reputation: 135992
I would implemented it as
public class Cache<K, T> implements ICache<K, T> {
Map<K, T> map = new HashMap<K, T>();
@Override
public boolean containsKey(K k) {
return map.containsKey(k);
}
@Override
public T getValue(K key) {
return map.get(key);
}
@Override
public void remove(K key) {
map.remove(key);
}
@Override
public void put(K k, T t) {
map.put(k, t);
}
}
it as Adapter pattern
Upvotes: 2