Wednesday, August 14, 2019

Java 8: Method Reference

Method Reference is a shorthand notation of Lambda Expression.

For example, you want to add an ActionListener to a JButton actButton.

Before Java 8:

actButton.addActionListener(new ActionListener () {
      public void actionPerformed(ActionEvent e) {
            searchButton.requestFocusInWindow();
      }
});


Use Lambda Expression:

actButton.addActionListener((ActionEvent e) -> {
      searchButton.requestFocusInWindow();
});


Use Method Reference:

actButton.addActionListener(searchButton::requestFocusInWindow());

If the method you are referencing is a member of the current class, it is also known as Memeber Reference.

For example, you are working in a class that is a subclass of the JFrame. After you have done some modification of the GUI, you want to call the pack() method.

javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
            this.pack();
      }
}


Use Memeber Reference:

javax.swing.SwingUtilities.invokeLater(this::pack());

The method called in Method Reference can be ordinary instance member of a class as shown in our above examples, a static method of a class, or even a constructor of a class, as long as the signature of the method exactly matches the method in the functional interface.

To reference a static method:

javax.swing.SwingUtilities.invokeLater(ResultCalss::print());

It requires the signature of the method print() matches the signature of the run() method in the Runnable interface.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Reference:
Method References in Java 8


No comments:

Post a Comment