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