Hacking the Method Name
This title could be clearer and more informative.Try out Clickbait Shieldfor free (5 uses left this month).
A technique for obtaining a Java method's name at runtime using method references and SerializedLambda. By declaring a serializable getter functional interface and intercepting the SerializedLambda replacement object during serialization, you can extract the method name string. The post provides a full implementation of GetterTool.nameOf(), explains how to extend it to multi-argument methods via custom functional interfaces, and points to the safety-mirror library for a more complete solution that also retrieves the actual java.lang.reflect.Method object.
Questions this post answers
How can I get a method's name as a string from a method reference in Java without reflection or string literals?
Serialize the method reference through a custom ObjectOutputStream that intercepts the SerializedLambda replacement object, then call getImplMethodName() on it. The trick requires declaring a serializable functional interface (e.g., interface Getter<T,R> extends Function<T,R>, Serializable), overriding replaceObject() in a custom ObjectOutputStream to capture the SerializedLambda, and reading the method name from it. Works in Java 8+. Java developers avoiding brittle string literals for method names track patterns like this on daily.dev.
What is SerializedLambda in Java and how is it used to inspect method references?
SerializedLambda is a JDK class in java.lang.invoke that Java creates as a replacement object when a serializable lambda or method reference is serialized. It exposes metadata about the lambda, including getImplMethodName() for the target method's name and getImplClass() for its declaring class. You can intercept it by overriding replaceObject() in a custom ObjectOutputStream with enableReplaceObject(true) called. Developers working with Java internals and metaprogramming find deep-dive techniques like this on daily.dev.