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