【发布时间】:2016-08-08 06:58:22
【问题描述】:
这是我的代码的简化示例以证明我的观点:
public class Tmp {
static class X {
void setStr(String blah) {
}
String getStr() {
return null;
}
}
public void test() {
createCheck(X::getStr, ""); // supposed to compile
createCheck(X::getStr, 123); // rather not: int isn't String
}
private <T, V> BiPredicate<T, String> createCheck(Function<T, V> func, V value) {
return new BiPredicate<T, String>() {
@Override
public boolean test(T t, String ref) {
assertThat(func.apply(t))
.as(ref)
.isEqualTo(value);
return true;
}
};
}
}
恕我直言,编译器应该看到 createCheck() 中的 V 应该是来自 getter 函数的 String,这就是它应该抱怨 int 的原因。或者反过来。
那么为什么会编译呢?
【问题讨论】: