我有泛型接口:
public interface Cache<CachePrimaryKey extends Object, RowModel extends CacheRowModel>
我需要创建扩展Cache的子接口,但在保留泛型的同时添加新方法。保留泛型部分的正确语法是什么?
我有实现之类的。
public class InfoCache implements Cache<Long, DataRowModel>
我试过了
public interface EnrichedCache<CachePrimaryKey extends Object,
RowModel extends CacheRowModel> extends Cache
但是,当我将InfoCache类的接口从Cache更改为EnrichedCache时,我得到的是“不覆盖其超类中的方法”。如果我在IntelliJ中使用“实现方法”,而不是Long + DataRowModel的方法,它将提供Object和CacheRowModel的方法(这不是我想要的)。
继承接口并保留所有泛型的正确方法是什么?
首先,我们使用大写字母表示泛型,这是为了避免出现以下废话:
public interface Cache<String> {
String getKey();
}
做你的事情上面interface
呢?
因此,将您的内容重写interface
为:
public interface Cache<K, R extends CacheRowModel>
请注意,这extends Object
是胡说八道,我已将其删除
然后创建一个interface
将extends Cache
保持相同泛型的泛型,我们将执行以下操作:
public interface EnrichedCache<K, R extends CacheRowModel> extends Cache<K,R>
也就是说,我们有一个泛型interface
,该泛型的参数K
(可以是任意值)和R
(必须是的子类CacheRowModel
)extends Cache
具有相同的参数。
您也可以加强传递的泛型:
public interface NumericCache<K extends Number, R extends CacheRowModel> extends Cache<K,R>
在这里,我们需要为关键NumericCache
来extends Number
。
您还可以将一个通用参数设置为具体类型,然后传递第二个:
public interface StringCache<R extends CacheRowModel> extends Cache<String, R>
在这里,我们将继承的缓存的键显式设置为,String
但允许用户指定CacheRowModel
使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句