我一直在阅读Java中的通配符,但我无法弄清楚在接口方法声明的实现中如何解决集合的通配符类型。您可以在技术上通过检查集合中的某个对象来发现该类型,但这不会允许您解决集合中的类型,并且如果该集合为空,则会失败。在接口的@Override实现中解析通配符类型
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;
}
}
}
有没有一种合适的方法我不知道这样做?
没有,因为类型擦除,有没有办法恢复运行时的原始类型。即使你的建议不起作用,因为'List
@TavianBarnes好点,我在那里做了一个糟糕的假设。 – nukeforum