3

Here's the scenario.

Our app has a very trivial interface for cache implementations, with methods similar to a Map:

public interface ICache<K, V> {

To add a concrete cache implementation we implement the interface and wrap a cache framework like EHCache, Redis, memcached etc. Example (the fact that its EHCache here is immaterial to the question):

public abstract class EHCacheWrapper<K,V> implements ICache<K, V> {

Next we have an implementation of EHCacheWrapper called AuthenticationCache:

public class AuthenticationCache 
   extends EHCacheWrapper<AuthenticationCacheKey, AuthenticationCacheEntry> {

So far so good.

The AuthenticationCache object has some additional methods beyond EHCacheWrapper or ICache. What we want to add are interfaces for AuthenticationCache, AuthenticationCacheKey, and AuthenticationCacheEntry:

public interface IAuthenticationCacheKey extends Serializable {
public interface IAuthenticationCacheEntry extends Serializable {
public interface IAuthenticationCache extends ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>{

So now we have:

public class AuthenticationCache 
   extends EHCacheWrapper<AuthenticationCacheKey, AuthenticationCacheEntry> 
   implements IAuthenticationCache {

Which gives the compiler error:

The interface ICache cannot be implemented more than once with different arguments: ICache<AuthenticationCacheKey,AuthenticationCacheEntry> and ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>

How do I achieve what we're after here?

Richard Sand
  • 642
  • 6
  • 20
  • 1
    You cannot implement the same interface with different generic bounds. The only ways I see fixing this are: --- to make the `IAuthenticationCache` generic in `K extends IAuthenticationCacheKey, E extends IAuthenticationCacheEntry` and let it implement `ICache`... I think you get the point or --- let `AuthenticationCache extends EHCacheWrapper`. – Turing85 May 04 '18 at 20:29
  • 1
    Possible duplicate of [how can I implement Comparable more than once?](https://stackoverflow.com/questions/2685537/how-can-i-implement-comparable-more-than-once) – VeeArr May 04 '18 at 21:06
  • Turing85 your suggestion worked - I changed IAuthenticationCache interface as follows: public interface IAuthenticationCache extends ICache { – Richard Sand May 04 '18 at 21:40

1 Answers1

4

As generics are no longer available at run time because of Type Erasure it can't be distinguished between two implementations of ICache<K, V>. You need to re-consider the design of you Interface and class hierarchy. Is it really necessary that IAuthenticationCache extends ICache?

public interface IAuthenticationCache
//extends ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>
{ ... } 
milbrandt
  • 1,438
  • 2
  • 15
  • 20
  • Yes because it gets passed into another object that accepts ICache - but I understand your point and agree I need to reconsider the design here – Richard Sand May 04 '18 at 21:36