asymptotically asymptotically - 1 year ago 87
Java Question

Get closure information from Java functional interface

I'd like to be able to access closure environment information at runtime from a Java functional interface. For example, I'm passing in a lambda, say,

(input) -> input + knownVariable
to a function

Now, from within
, I'd like to be able to access the environment associated with this lamdba, and get the value of all the variables stored in this environment.

Is this possible? I don't mind having to create my own functional interface, or use reflection, etc.

I want the final output to be something like a map of
variable name -> value/address
. So I should be able to do this:

void lambdaProcessor(FunctionalInterfaceInstance l) {

And it should print out

{"knownVariable": 10, ... }

Or even if it doesn't store variable names and just stores some kind of marker, I'd still like

{"reference1": 10, ... }

Answer Source

You can retrieve captured variables from the generated lambda class using reflection. Note that this is very brittle, since the lambda class structure is unspecified and can change at any time (or may not even exist). Example:

static void printCaptures(Function<Integer, String> f) throws Exception {
    for (Field field : f.getClass().getDeclaredFields()) {
        System.out.println(field.getName() + ": " + field.get(f));

Ideone Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download