This is my solution (inspired by the andersschuller solution at fooobar.com/questions/969406 / ... ) for the problem. There may be some Classloading cases where this implementation does not work, but for the simplest cases it works.
I created a small performance test with my limited knowledge of jmh: https://gist.github.com/picpromusic/4b19c718bec5a652731a65c7720ac5f8
"Named" results are measured to implement @stuartmarks answer. Naming (toString) lambda expressions for debugging purposes
As you can see, this is about 2 times slower than using an unnamed lambda. Therefore, be careful when setting -DnamedLambdasEnabled = true. The premonition for me is that calling βStringβ on Real Lambda is surprisingly expensive. Maybe someone can explain this, or my jmh test is stupid.
Here is the code:
public class LambdaNamer { private static Method TO_STRING; static { try { TO_STRING = Object.class.getMethod("toString"); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException("There is something rotten in state of denmark!"); } } public static <T> T nameIt(String name, T obj) { if (Boolean.getBoolean("namedLambdasEnabled")) { Class<T> clazz = (Class<T>) obj.getClass(); Class<?>[] interfaces = clazz.getInterfaces(); return (T) Proxy.newProxyInstance(
Do you have other solutions? Maybe something that does not affect performance?
source share