我正在使用几个带有泛型类型的接口。在将它们组合在一起时,我不得不从一部分不知道泛型参数的具体类型的代码中使用它们时遇到一些问题。具有未知通用类型接口的Java通用编程
假设我有以下接口:
public interface MyObjectInterface<T extends Number> {}
执行该interfaceare存储在一个泛型集合有相同的通用类型的对象:MyCollectionInterface的
public interface MyCollectioninterface<T extends Number> {
public void updateObject(MyObjectInterface<T> o);
}
具体事例举行的几个MyObjectInterface相同的通用参数:
public class ConcreteCollection<T extends Number> implements
MyCollectionInterface<T> {
List<MyObjectInterface<T>> list;
public void updateObject(MyObjectInterface<T> o){}
}
现在,我有几个关于如何使用这些通用接口的问题,该客户类是 (并且必须)不知道泛型的具体类型。
假设我有以下类:
public class ClientClass{
private MyCollectionInterface<?> collection; //1st possibility
private MyCollectionInterface collection; //2nd possibility
public ClientClass(MyCollectionInterface<?> collection){
this.collection = collection;
}
public void foo(MyObjectInterface<?> o){
this.collection.updateObject(o); //this doesn't compile
}
public void foo(MyObjectInterface<? extends Number> o){
this.collection.updateObject(o); //this doesn't compile either
}
public void bar(MyObjectInterface o){
MyObject b = o; //warning
this.collection.updateObject(o); //this compile but with warnings
}
}
首先问:
- 考虑一个事实,即ClientClass不关心其具体类型扩展号码是收藏,我应该申报收集有无“?” ?如果使用第二个版本,我会收到以下警告:
MyCollectionInterface是一种原始类型。引用泛型类型 LatticeInterface应该是参数
第二个问题:
- 为什么foo方法无法编译?
第三个问题:
- 看来,我需要用吧签名调用updateObject方法。无论如何,这个解决方案在尝试分配MyObjectInterface参数时会产生警告,就像第一个问题一样。我可以删除此警告吗?
最后的问题:
- 我在做一些奇怪这个通用接口,我应该重构我的代码?我真的不得不关心所有这些警告吗?
- 如何从一个不知道具体类型的类使用安全通用接口?
什么是MyObject? –
不应该在'foo'和'bar'方法中使用'MyObjectInterface'而不是'MyObject'吗? – guardianpt
是的,我的错。我修好了它。它是MyObjectInterface。 – Heisenbug