2013-12-13 232 views
0

我試圖實現Apache Shiro CacheManager interface。它的唯一方法具有以下特徵:Java類型參數混淆

<K,V> Cache<K,V> getCache(String name) throws CacheException 

似乎最左邊的<K, V>類型參數有效告訴編譯器,K和V是「類型」。我的問題是這樣的:我如何返回該類型的實例?當我嘗試下面的代碼,Eclipse的抱怨,K和V不能被解析爲類型:

public class ShiroGuavaCacheManager implements CacheManager 
{ 
    private Cache<K, V> cache; // <--- The compiler complains here 

    @Override 
    public <K, V> Cache<K, V> getCache(String name) throws CacheException 
    { 
     return (cache != null) ? cache : new ShiroGuavaCache<K, V>(); 
    } 
} 
+0

如果要定義自己的類,它具有與參數化類型類的成員,你需要做的類參數,即'public class ShiroGuavaCacheManager implements CacheManager' ...在這種情況下,你可能想要從getCache聲明中刪除第一個'';您不需要使用與該類使用的參數相同的參數來對參數化方法進行參數化。如果你不知道我在說什麼,需要解釋什麼是泛型,請告訴我們。 – ajb

回答

1

在你ShiroGuavaCacheManager類,KV沒有定義。所以,如果你想使ShiroGuavaCacheManager通用,它會像

public class ShiroGuavaCacheManager<K,V> implements CacheManager 
{ 
    private Cache<K, V> cache; // without the class level K,V definitions, K and V are not known types 

    @Override 
    public Cache<K, V> getCache(String name) throws CacheException 
    { 
     return (cache != null) ? cache : new ShiroGuavaCache<K, V>(); 
    } 
} 

然後,你可以創建例如new ShiroGuavaCacheManager<String,String>()



當你有一個定義類似類型的方法如下(如在原班):

public <K, V> Cache<K, V> getCache(String name) 

這工作,因爲你決定KV是根據你所指定的是什麼至。所以,你可以做

Cache<String,String> = getCache("mycache"); 

這些只是被稱爲通用的方法,http://docs.oracle.com/javase/tutorial/java/generics/methods.html

+0

這工作,但它導致了警告:「類型安全:從類型ShiroGuavaCacheManager 選中需要轉換爲getCache(string)的返回類型緩存從類型的CacheManager符合緩存<對象,對象>」我可以添加@SuppressWarnings(「unchecked」),但是這樣做的含義是什麼? –

+1

這是因爲你已經改變了'getCache'的定義,因爲你不再定義與方法內聯的通用變量,而且它們隱含地是'Object'。我認爲,如果您嘗試在定義getCache之前將K,V放回原處,編譯器會抱怨您正在重新定義K和V(但您可以嘗試確定)。我不認爲這有一個乾淨的解決方法,但我不是一個泛型專家,所以也許別人可以添加到這個。 –