[FIXED] Java – method reference for setter and getter

Issue

A Pojo 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:

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);
    }
}
  1. How do we interpret the java lambda used for setter?
    BiConsumer<T, R> functional interface has been used for parameter type for setField and Person::setName was passed as parameter value for the method.
    My understanding of BiConsumer<T, R> is that its a functional interface used to denote the lambda function with two input parameters and no return parameter i.e., (a,b) -> a+b;
    where a+b could be any logic(sequence of steps that uses a and b parameters).
    But in the above code example BiConsumer<T, R> denotes the lambda function (personObject,nameValue) -> personObject.set(nameValue);
  2. How do we interpret the java lambda used for getter?
    My understanding Function<T,R> = (a) -> return math(a);
    Whereas in the above code example Function<T,R> = (personObject) -> return personObject.getName();

Can I get help to understand that above two interpretations please.

Solution

  1. Exactly, a BiConsumer consumes 2 things. [A] An instance of the Person class, and [B] the value for the name field to set.

  2. Yup. The input is an instance of Person, the output is the name of that person.

The key realization is that the getter lambda represents the getter itself without an actual person instance associated with it. 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.

Answered By – rzwitserloot

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published