【发布时间】:2011-09-04 15:17:44
【问题描述】:
我正在使用几个具有泛型类型的接口。在将它们组合在一起时,当我不得不从不知道泛型参数的具体类型的部分代码中使用它们时,我遇到了一些问题。
假设我有如下界面:
public interface MyObjectInterface<T extends Number> {}
实现该接口的对象存储在具有相同泛型类型的泛型集合中:
public interface MyCollectioninterface<T extends Number> {
public void updateObject(MyObjectInterface<T> o);
}
MyCollectionInterface 的具体实例包含相同泛型参数的多个 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 不关心扩展 Number 的具体类型是集合,我应该用“还是不带”声明集合? ?如果我使用第二个版本,我会收到以下警告:
MyCollectionInterface 是原始类型。对泛型类型的引用 LatticeInterface 应该被参数化
第二个问题:
- 为什么方法 foo 不能编译?
第三题:
- 看来我需要使用 bar 签名来调用 updateObject 方法。无论如何,此解决方案在尝试分配 MyObjectInterface 参数时会产生警告,就像在第一个问题中一样。我可以删除此警告吗?
最后的问题:
- 我是否对这个通用接口做了一些奇怪的事情,我应该重构我的代码?
- 我真的需要关心所有这些警告吗?
- 如何安全地使用我不知道其具体类型的类中的泛型接口?
【问题讨论】:
-
在方法
foo和bar中不应该是MyObjectInterface而不是MyObject吗? -
是的,我的错。我修好了它。它是 MyObjectInterface。
标签: java generics interface raw-types