带参数的方法引用 [英] Method references with a parameter
本文介绍了带参数的方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 8中,使用以下类
In Java 8, with the following class
class Person {
private boolean born;
Person() {
}
public void setBornTrue() {
born = true;
}
public void setBorn(boolean state) {
born = state;
}
}
可以调用setBornTrue通过方法参考的方法:
it is possible to call the setBornTrue method via a method reference:
ArrayList<Person> people = new ArrayList<>();
people.add(new Person());
people.forEach(Person::setBornTrue);
但我如何使用forEach方法并使用方法参考>使用setBorn ?尝试:
but how would I use the forEach method and use the setBorn using a method reference? Trying:
people.forEach(Person::setBorn);
导致错误,无法解析方法setBorn。
results in an error, "Cannot resolve method setBorn".
此外,我如何传递True的值?
In addition, how would I pass in the value of True?
推荐答案
使用lambda:
people.forEach((p) -> p.setBorn(true));
发现没有其他方法只使用java 8 API。
Found no other ways only using the java 8 API.
使用此自定义函数:
public static <T, U> Consumer<T> bind2(BiConsumer<? super T, U> c, U arg2) {
return (arg1) -> c.accept(arg1, arg2);
}
你可以这样做:
people.forEach(bind2(Person::setBorn, true));
如果java API或库中提供了这种实用工具方法,请告诉我们。
If this kind of utility methods is available in the java API or in a library, please let us know.
这篇关于带参数的方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文