Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Friday, February 12, 2016

Java 8 Method References for Concise Object Initialization

This is a code snippet showing a usage of Java 8 Method References.  A JavaFX Stage is initialized with a sequence of setters.  Rather than use anonymous inner classes or even Lambdas to set a pair of window lifecycle handlers, I use Method References to keep the block of setters aligned.  This is especially useful if the indentation of spacing of inlined class and method definitions causes the text to shift and become less readable.


This post was inspired by Gerrit Grunwald's JavaOne video.

To read more about Method References, visit the Java Tutorials section at this link.  This post demonstrates the "Reference to an instance method" concept.

The following JavaFX program displays a titled Stage containing a single "Method References" Label.  I've registered two handlers for the onShowing and onHiding events.  I could have coded this using pre-Java 8 anonymous inner classes or Java 8 Lambdas, but this would have broken up the flow of the initialization.

public class MethodRefMain extends Application {

  public void start(Stage primaryStage) throws Exception {
    Label label = new Label("Method References");
    Scene scene = new Scene(label);
    primaryStage.setScene( scene );
    primaryStage.setTitle("Method References");

  public void handleShowing(WindowEvent evt) { System.out.println("showing..."); }
  public void handleHiding(WindowEvent evt) { System.out.println("hiding..."); }
  public static void main(String[] args) { launch(args); }

The "this" in the setOnShown() and setOnHiding() calls refers to the JavaFX Application instance.  The handleOnShowing/Hiding point to methods matching the expected call signature (WindowEvent).

The savings of a single-line method versus a Lambda (ex, "evt -> System.out.println") isn't that compelling.  However, if the functions I expected to call were more than one line, then it's easy to see how the nesting an multiple lines would chop up my calls on the primaryStage object.

No comments:

Post a Comment