[英]Java type parameter confusion
我正在尝试实现Apache Shiro CacheManager接口 。 其唯一方法具有以下签名:
<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>();
}
}
在您的ShiroGuavaCacheManager
类中,未定义K
和V
因此,如果您想使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)
之所以有效,是因为您根据分配给K
和V
来决定K
和V
所以你可以做
Cache<String,String> = getCache("mycache");
这些被称为通用方法http://docs.oracle.com/javase/tutorial/java/generics/methods.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.