Saturday, October 17, 2015

Method reference operator in Java 8

Here is the code:

package sample;

import java.beans.PropertyChangeEvent;

/**
 * Created by IDEA on 28/07/15.
 */
public class EmployTest {
    public static void main(String[] args) {
        final Employee e1 = new Employee("John Jacobs",
                20000.0);
        e1.addPropertyChangeListener(EmployTest::handlePropertyChange);
        e1.setSalary(300.01);
        e1.setSalary(300.02);
        e1.setSalary(300.03);
    }

    private static void computTax(double salary) {
        final double TAX_PERCENT = 20.0;
        double tax = salary * TAX_PERCENT / 100.0;
        System.out.println("Salary: " + salary +
                "\nTax: " + tax);
    }

    public static void handlePropertyChange(
            PropertyChangeEvent e) {
        String propertyName = e.getPropertyName();
        if("salary".equals(propertyName)) {
            System.out.println("Salary has changed" + "\n" +
            "Old: " + e.getOldValue() + "\n" +
            "New: " + e.getNewValue());
            computTax((Double) e.getNewValue());
        }
    }
}

Notice the EmployTest::handlePropertyChange part:

It’s the method reference operator. In this case, the method handlePropertyChange from the EmployeeTest class is referenced. The addPropertyChangeListener takes a PropertyChangeListener object, which has a single method that returns void and takes a stPropertyChangeEvent as an argument. The handlePropertyChange method in your code satisfies that contract, so a method reference to it is a shorthand for creating an (anonymous) inner class with the same method in that place.

Ah, I see. Almost looks like passing functions around in Scala/Clojure etc.

Yeah, that’s pretty much what it is. Was introduced in java8 along with the whole lambda-deal

0 comments: