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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With