[英]Java - method reference for setter and getter
A Pojo class:宝卓class:
package com.lambda.jay;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Another class for initiating 'Person' objects:另一个 class 用于启动“Person”对象:
package com.fi.lambda.jay;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class Actor {
public <T,R> void printField(T obj, Function<? super T,? extends R> getter1) {
System.out.println(getter1.apply(obj).toString());
}
public <T,R> void setField(T obj, R value, BiConsumer<T, R> setter) {
setter.accept(obj, value);
}
public static void main(String[] args) {
Person person = new Person();
Actor actor = new Actor();
actor.setField(person, "Bob", Person::setName);// (a,b) -> a.setB(b);
actor.printField(person, Person::getName);
}
}
Can I get help to understand that above two interpretations please.请帮助我理解以上两种解释。
Exactly, a BiConsumer
consumes 2 things.确切地说,一个
BiConsumer
消费了 2 样东西。 [A] An instance of the Person
class, and [B] the value for the name
field to set. [A]
Person
class 的一个实例,以及 [B] 要设置的name
字段的值。
Yup.是的。 The input is an instance of
Person
, the output is the name of that person.输入是
Person
的一个实例,output 是那个人的名字。
The key realization is that the getter
lambda represents the getter itself without an actual person instance associated with it.关键的实现是
getter
lambda 表示 getter 本身,没有与之关联的实际人员实例。 If you do want that, you can;如果你确实想要,你可以; something like
somePersonInstance::getName
is a Producer
(takes no inputs and provides an output), whereas something like Person::getName
is a Function, takes 1 Person
instance and provides an output.类似
somePersonInstance::getName
的东西是Producer
(不接受输入并提供输出),而类似Person::getName
的东西是 Function,需要 1 个Person
实例并提供 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.