This question already has an answer here:
- Printing debug info on errors with java 8 lambda expressions 1 answer
- Reflection type inference on Java 8 Lambdas 5 answers
- How to get the MethodInfo of a Java 8 method reference? 10 answers
I've been using a lot of method references and lambdas recently, and wanted to know at runtime if i could print to screen the source of the lambda ie its name, simply for debugging reasons. I figured it might be possible using reflection, by calling getClass() within getName(), but I couldn't find a method with which to find the original source reference's name.
I have a functional interface such as:
@FunctionalInterface
public interface FooInterface {
// function etc etc irrelevant
public void method();
public default String getName() {
// returns the name of the method reference which this is used to define
}
}
then lets say i wish to test run the interface, and print the source of the functional interface to the screen.
public static void doStuff(FooInterface f) {
// prints the lambda name that is used to create f
System.out.println(f.getName());
// runs the method itself
f.method();
}
So that if i do this:
doStuff(Foo::aMethodReference);
it should print something like: "aMethodReference" to the screen, that way i can know, at runtime which methods are being run, in what order etc.
I'm quite doubtful that this is possible, considering that lambdas are not-quite-objects, but hey, i figured there could be a workaround. Furthermore, the eclipse debug tool just says its a lambda, without any other information, do lambda's retain any of this information? or is it all lost at Runtime?
Cheers. (I'm using JDK 11 if that makes any difference)