Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java Lambdas to replace javafx builders

I'm a big fan of the Javafx 2 builder notation, however it has been deprecated in Java 8 and I need to replace my old code in a large codebase. I'd like to keep a similar programming style. Now I could use double brace initialization, but I don't like creating so many anonymous inner classes and I found it can sometimes cause issues with certain classes. I figured there has to be a way to use lambda to accomplish something similar and came up with this.

public class FXUtil {
  public static <T> T build(T node, Consumer<T> initializer) {
    initializer.accept(node);
    return node;
  }
}

So now I can replace my builders like so

Label label = FXUtil.build(new Label(), label -> {
  label.setText("Text");
  label.setStyle("-fx-font-size: 20");
  label.setMinWidth(100);
});

This is not quite as nice as the builder or the double brace syntax, but better than nothing. My question is does this have any drawbacks similar to double brace initialization? The object itself is not an anonymous class, but am I essentially doing the same thing by creating an anonymous class for the lambda? The lambdas should be garbage collected, correct? Do I even need to worry about this now that permgen space is gone in JDK8? Does anyone else have better way of initializing javafx classes besides using FXML?

Edit: updated example with suggestion from @BenjaminGale

like image 931
Brian Blonski Avatar asked Oct 21 '22 01:10

Brian Blonski


1 Answers

I assume the drawback you're referring to with double brace initialization is that as an inner class it captures a reference to the enclosing class in which it was created. The lambda will not do that. (And, on the Oracle Hotspot JVM, it is not compiled to an anonymous inner class, either.)

like image 189
David Conrad Avatar answered Oct 23 '22 09:10

David Conrad