I will try to be very careful here with my wording, as a lambda is essentially just a method signature and body.
The premise for my question is that it would be very useful to be able to keep the concise syntax lambda, and to be able to have a human-readable name (string) to identify it, i.e. when you log it out.
Previously, with anonymous classes I could always override toString.
final Runnable runnable = new Runnable() {
@Override public void run() { System.out.println("1"); }
@Override public String toString() { return "anonymous-1"; }
}
Scenarios
The following are scenarios where I have found myself needing to revert back to code to be able to deciper
The problem As there is no accompanying toString then all you get in the logs when you try to log out the lambda reference, for example:
MyClass$$Lambda$1/424058530@1c20c684
Approaches
Appreciate people's thoughts and experiences in and around this.
Here's a middle ground that is a little more syntactically compact that just going back to inner classes -- a Runnable-with-toString factory.
static Runnable makeRunnable(Runnable r, Supplier<String> toStringFn) {
return new Runnable() {
public void run() { r.run(); }
public String toString() { return toStringFn.get(); }
};
}
Now, at the use site, you do:
Runnable r = makeRunnable(() -> System.out.println("1"),
() -> "anonymous-1");
(If you have no reason to believe that the toString method will need access to any state, you can just turn the second argument into String
instead of Supplier<String>
.)
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