请使用类名解释Java 8方法参考实例方法 [英] Please Explain Java 8 Method Reference to instance Method using class name
问题描述
public interface MyFunc<T> {
boolean func(T v1, T v2);
}
public class HighTemp {
private int hTemp;
HighTemp(){
}
public HighTemp(int ht) {
this.hTemp = ht;
}
boolean sameTemp(HighTemp ht2){
return hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2){
return hTemp < ht2.hTemp;
}
}
class InstMethWithObjRef {
static <T> int counter(T[] vals, MyFunc<T> f, T v){
int count = 0;
for (int i = 0; i < vals.length; i++) {
if(f.func(vals[i], v)) count++;
}
return count;
}
public static void main(String[] args) {
int count;
//Create an array of HighTemp objects.
HighTemp[] weekDayHighs = {new HighTemp(89), new HighTemp(82),
new HighTemp(90), new HighTemp(89),
new HighTemp(89), new HighTemp(91),
new HighTemp(84), new HighTemp(83)};
count = counter(weekDayHighs, HighTemp::lessThanTemp,new HighTemp(89));
System.out.println(count);
}
}
请说明如何
-
boolean sameTemp()
与func()
兼容在功能界面中。 -
sameTemp()
方法在func()
在功能界面中。 -
count = counter(weekDayHighs,HighTemp :: sameTemp,new HighTemp(89));
正在运行
boolean sameTemp()
is compatible withfunc()
in Functional interface.sameTemp()
method got implemented onfunc()
in Functional Interface.count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
is working
请分别解释所有要点。
推荐答案
等价 的lambda表达式HighTemp :: lessThanTemp
是
(highTemp1, highTemp2) -> {
return highTemp1.lessThanTemp(highTemp2);
}
这是 Java8的功能之一
命名为 参考任意实例方法特定类型的对象
This is one of the features of Java8
named Reference to an Instance Method of an Arbitrary Object of a Particular Type
请考虑以下示例,
interface FIface<T> {
int testMethod(T a, T b);
}
class Test2 {
private String str;
Test2(String str) {
this.str = str;
}
int ok(Test2 test2) {
System.out.println("Currnet String : "+ this.str);//Refer to t1
System.out.println("Test String : "+test2.str);//Refer to t2
return 0;
}
}
public class Test {
public static <T> int checkCall(T t1, T t2, FIface<T> fiFace) {
//Here Test2 :: ok is equivalent to t1.ok(t2)
return fiFace.testMethod(t1, t2);
}
public static void main(String[] args) {
checkCall(new Test2("a"), new Test2("b"), Test2 :: ok);
}
}
OUTPUT
Currnet String : a
Test String : b
请注意, Test2 :: ok
对该电话有效,即使 ok
方法不是静态的。
Note here that Test2 :: ok
is valid for the call even ok
method is not static.
当您为函数接口调用方法 checkCall
时,您仍然有两个参数 t1
和 t2
,对于该有效的lambda表达式,参数可以为(测试t1,测试t2)
所以你的方法 Test2 :: ok
这里对这个电话有效。在内部它以这种方式工作 t1.ok(t2)
。
When you call the method checkCall
for the functional interface you still have two arguments which are t1
and t2
and for that valid lambda expression can have parameters as (Test t1, Test t2)
so your method Test2 :: ok
here becomes valid for the call. Internally it works this way t1.ok(t2)
.
所以, fiFace。 testMethod(t1,t2);
将调用方法为 t1.ok(t2)
这篇关于请使用类名解释Java 8方法参考实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!