作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码的一个简短示例来证明我的观点:
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。或者反过来。
那么为什么会编译呢?
最佳答案
您的签名是:
private <T, V> BiPredicate<T, String> createCheck(Function<T, V> func, V value) {
您对 T
没有限制或 V
所以绝对是 T
的任何值或 V
会编译。
您返回一个BiPredicate<T, String>
然而,所以 isEqualTo
方法采用 String ref
并将其与 Object value
的相等性进行比较- 我认为这也是完全合法的isEqualTo
需要 Object
模仿 Object.equals
的行为.
在你的例子中:
createCheck(X::getStr, 123);
V
就是Object
因为这是可以应用于 String
的最严格的类型限制和 Integer
.
您的意思是:
private <T> BiPredicate<T, String> createCheck(Function<T, String> func, String value) {
关于java - Lambda 和泛型 : Why Does This Compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38822972/
我是一名优秀的程序员,十分优秀!