Java 8功能接口分配上下文 [英] Java 8 Functional interface assignment context
问题描述
问题在于功能接口的分配上下文-
Question is regarding assignment context of functional interface-
Predicate<String> p = String::isEmpty;
在String类中的isEmpty
方法声明为-public boolean isEmpty(){}
时工作正常.
Works fine where the isEmpty
method declaration in String class is - public boolean isEmpty(){}
.
如果我尝试在自定义类中声明相同的内容-
If I try to declare same in custom class like -
class Test{
public boolean isEmpty(){
...
}
}
并进行相同的分配-
Predicate<String> p = Test::isEmpty;
这将是编译错误-
Test类型未定义适用的isEmpty(String) 这里
The type Test does not define isEmpty(String) that is applicable here
Predicate<T>
表示一个参数的谓词(布尔值函数),函数方法为boolean test(T t){}
.
And Predicate<T>
represents a predicate (boolean-valued function) of one argument and functional method is boolean test(T t){}
.
有什么解释吗?而且我想念什么吗?
Any explanation? And am I missing anything?
推荐答案
您应该具有:
Predicate<Test> p = Test::isEmpty;
而不是
Predicate<String> p = Test::isEmpty;
class Test {
public boolean isEmpty(){
...
}
}
那为什么要有Predicate<String>
?
请参见方法引用指南.这里的情况是第三种情况对特定类型任意对象的实例方法的引用".
See the tutorial of method references. What you have here is the 3rd case "Reference to an instance method of an arbitrary object of a particular type".
拥有
Predicate<String> p = String::isEmpty();
String s = "";
调用p.test(s);
与callign s.isEmpty();
相同,因此这就是为什么不能给String
作为参数来调用Test
中的方法的原因.
Calling p.test(s);
is the same as callign s.isEmpty();
so that's why you cannot give as argument a String
to call a method from Test
.
如果String
和Test
都将使用方法boolean isEmpty()
实现接口Empty
,然后具有Predicate<Empty>
,则有可能具有通用的Predicate
.然后p.test(string)
和p.test(test)
都可以工作;否则,Java不会具有强类型,并且不支持鸭子类型.
It would have been possible to have a common Predicate
if both String
and Test
would implement an interface Empty
with the method boolean isEmpty()
and then to have Predicate<Empty>
. Then both p.test(string)
and p.test(test)
would work; otherwise it won't, Java has strong typing and does not support duck typing.
这篇关于Java 8功能接口分配上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!