我一直在阅读Java中的Wildcards,但我无法弄清楚如何在接口方法声明的实现中解析Collection的Wildcard类型。您可以通过检查Collection中的一个对象从技术上发现类型,但这不允许您解析Collection中的类型,如果Collection为空,它将失败。
public interface SomeInterface {
void addAThing(Object thing);
void addAListOfThings(Collection< ?> things);
}
public class SomeInterfaceImplementation implements SomeInterface {
@Override
public void addAThing(Object thing) {
if (thing instanceof Foo) {
/* thing has been discovered to be of type Foo
so now it can be assigned to an explicit Foo object */
Foo fooThing = (Foo) thing;
}
}
@Override
public void addAListOfThings(Collection< ?> things) {
//this fails if things is empty
if (things.toArray()[0] instanceof Foo) {
/* things type has been discovered(maybe) to be of type Foo
but now we are unable cast without an unchecked cast exception */
Collection<Foo> fooThings = (Collection<Foo>) things;
}
}
}
是否有一个我不知道这样做的正确方法?
答案 0 :(得分:3)
如果您希望您的方法使用泛型,则应在签名或类/接口定义中定义。
public interface SomeInterface<T> {
void addAThing(T thing);
void addAListOfThings(Collection<T> things);
}
通用类型Foo
的实现类:
public class SomeInterfaceImplementation implements SomeInterface<Foo> {
@Override
public void addAThing(Foo thing) {
// thing is of type Foo
}
@Override
public void addAListOfThings(Collection<Foo> things) {
// things is a collection of Foo
}
}