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 ...

Saturday, February 14, 2015

Java 8 Streams Example Scanning Classes in an FX Project

Prior to Java 8 Streams, I would have coded this in two stages: sort, then process.  With Streams, I can sort in-line with a shorthand syntax.  This leads into a forEach() where the processing occurs.
This block of code uses the Reflections project to pull in a bunch of files marked up with my custom @SubApplication annotation.

Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setScanners(new TypeAnnotationsScanner()));

Set<Class<?>> subapps = reflections.getTypesAnnotatedWith(SubApplication.class);

subapps.stream().sorted(Comparator.comparing(Class::getName)).forEach(sa -> {

    SubApplication saAnnotation = sa.getAnnotation(SubApplication.class);

    Button btn = new Button(saAnnotation.buttonTitle());
    btn.setUserData(sa);  // holds the metadata    btn.setOnAction(evt -> startScreen(evt));


getTypesAnnotatedWith() returns a Set of Classes which is the basis for my processing.

I stream the Set into a sorted() stage.  Comparator.comparing is a static method that accepts the shorthand Class:getName.  This comparison will sort the classes by class name.  (the Reflections call doesn't return an alphabetically sorted list.)  The sorted list is funneled into a button-creating block.

By the time that the add to the VBox is made, the input is sorted and will appear in the proper order on the Stage.

No comments:

Post a Comment