我有以下通用功能接口:
@FunctionalInterface
public interface FooInterface<T> {
void bar(T arg);
}
而这个 ArrayList 后代:
public class FooList<T> extends ArrayList<FooInterface<T>> {
public void doFoo(T arg) {
for(Iterator<FooInterface<T>> i = iterator(); i.hasNext(); ) {
i.next().bar(arg);
}
}
}
现在,我使用方法引用和类型擦除来编写这段代码:
protected void doFoo(Object arg) { }
private void doStuff() {
FooInterface f = this::doFoo;
List<FooInterface> list = new ArrayList<>();
list.add(f2);
list.add(this::doFoo);
FooList list2 = new FooList();
list2.add(f2);
list2.add(this::doFoo); // <-- Compiler chokes here, complaining that this is not a FunctionalInterface
}
这让我很困惑。为什么编译器会同意我将 this::doFoo 分配给 FooInterface 变量,并在代码的第一部分调用 List.add() ,只是拒绝从 ArrayList 派生的类调用相同的 add() 方法?
在我的后代班级中,类型擦除似乎正在发生一些时髦的事情,但是什么?这是一个错误吗?我做了不支持的事情吗?