Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether lambda is a method reference

Tags:

java

lambda

Is there a way to determine whether a given Java lambda object is a method reference or a "CallSite-specific" lambda:

boolean isMethodReference(Object lambda)

Positive example:

assertTrue(isMethodReference(Object::toString));

Negative example with "CallSite-specific" lambda:

long valueFromCallSite = System.currentTimeMillis();
Consumer<Object> lambda = o -> {
    if (valueFromCallSite % 2 == 0) {
        o.toString();
    } else {
        o.hashCode();
    }
};
assertFalse(isMethodReference(lambda));
like image 755
Benedikt Waldvogel Avatar asked Jun 21 '26 11:06

Benedikt Waldvogel


1 Answers

A heuristic approach for isMethodReference(lambda) was proposed in "Determine if a lambda expression is stateless or stateful in Java":

boolean isMethodReference(Object lambda) {
    return lambda.getClass().getDeclaredFields().length == 0;
}

It’s only a heuristic because it relies on unspecified behavior and thus is JDK implementation-specific and even might break in a future version.

like image 96
Benedikt Waldvogel Avatar answered Jun 22 '26 23:06

Benedikt Waldvogel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!