假设我有一个界面
interface Foo<T> {
void foo(T x);
T bar()
}
以及具有未知参数的此类对象:Foo<?> baz
。然后我可以打电话baz.foo(baz.bar())
。
但是,现在我需要将值baz.bar()
放入一个集合baz.foo()
中,稍后再调用它。就像是
List<???> list; // can I tell the compiler this is the same type as baz's wildcard?
list.add(baz.bar());
...
baz.foo(list.get(1));
这也不起作用:
List<Object> list;
list.add(baz.bar());
...
baz.foo((???) list.get(1)); // I can't write down the type I need to cast to
有没有办法做到这一点?
编辑:以上内容从我的实际情况来看过于简单化了。说我们有
class Bar {
private final Foo<?> foo;
private List<???> list; // the type argument can be selected freely
Bar(Baz baz) {
foo = baz.getFoo(); // returns Foo<?>, can't be changed
}
void putBar() {
list.add(foo.bar());
}
void callFoo() {
foo.foo(list.get(0));
}
}