[cdi-dev] Adding Lambdas as CDI beans

David Blevins dblevins at tomitribe.com
Sat Oct 17 05:04:46 EDT 2015


In brainstorming mode about fun that could be made possible with Java 8 and Java EE.

Question in my mind is: is there some way we could make it possible for Lambdas or Method Refs to be CDI beans?

It goes against the grain obviously as CDI creation is very much a “Don’t call us, we’ll call you” kind of thing.  The VM dynamically creates a wrapper object around the Lambda or method reference and it implements the given interface.

To make it work, there would need to be some non-producer method way of saying “put this thing in the context with these qualifiers”.

Imagine a method somewhere that would allow you to:

    public <T> void addObserver(java.util.function.Consumer<T> observer, Annotation... qualifiers);


Then you could take advantage as follows:

    final List<URI> uris = new ArrayList<>();
    // @Observes URI
    addObserver((Consumer<URI>) uris::add);

    // @Observes Thread
    addObserver(Runtime.getRuntime()::addShutdownHook);

    // @Observes Runnable
    addObserver((Consumer<Runnable>) Executors.newFixedThreadPool(3)::submit);

    // @Observes URI
    addObserver((Consumer<URI>) System.out::println, new AnnotationLiteral<Fine>() {
    });

    // @Observes Handler
    final Logger logger = Logger.getLogger("somewhere");
    addObserver(logger::addHandler); // add handlers via event

    // @Observes @Fine String
    addObserver((Consumer<String>) logger::fine, new AnnotationLiteral<Fine>() {});
    }

    

-David




More information about the cdi-dev mailing list