Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics how to avoid interface cannot be implemented more than once with different arguments

Tags:

java

generics

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?

like image 311
Richard Sand Avatar asked May 25 '26 00:05

Richard Sand


1 Answers

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>
{ ... } 
like image 150
milbrandt Avatar answered May 27 '26 14:05

milbrandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!