[英]Java generics how to avoid interface cannot be implemented more than once with different arguments
這是場景。
我們的應用程序有一個非常簡單的緩存實現接口,方法類似於Map:
public interface ICache<K, V> {
為了添加具體的緩存實現,我們實現了接口並包裝了一個緩存框架,如EHCache,Redis,memcached等。例子(事實上,這里的EHCache對這個問題並不重要):
public abstract class EHCacheWrapper<K,V> implements ICache<K, V> {
接下來我們有一個名為AuthenticationCache的EHCacheWrapper實現:
public class AuthenticationCache
extends EHCacheWrapper<AuthenticationCacheKey, AuthenticationCacheEntry> {
到現在為止還挺好。
AuthenticationCache對象除了EHCacheWrapper或ICache之外還有一些其他方法。 我們要添加的是AuthenticationCache,AuthenticationCacheKey和AuthenticationCacheEntry的接口:
public interface IAuthenticationCacheKey extends Serializable {
public interface IAuthenticationCacheEntry extends Serializable {
public interface IAuthenticationCache extends ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>{
所以現在我們有:
public class AuthenticationCache
extends EHCacheWrapper<AuthenticationCacheKey, AuthenticationCacheEntry>
implements IAuthenticationCache {
這給出了編譯器錯誤:
The interface ICache cannot be implemented more than once with different arguments: ICache<AuthenticationCacheKey,AuthenticationCacheEntry> and ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>
我如何實現我們之后的目標?
由於類型擦除在運行時不再提供泛型,因此無法區分ICache<K, V>
兩個實現。 您需要重新考慮Interface和類層次結構的設計。 IAuthenticationCache
是否真的有必要擴展ICache
?
public interface IAuthenticationCache
//extends ICache<IAuthenticationCacheKey,IAuthenticationCacheEntry>
{ ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.