Skip to content

Instantly share code, notes, and snippets.

@jhorstmann
Last active May 12, 2023 08:05
Show Gist options
  • Save jhorstmann/de367a42a08d8deb8df9 to your computer and use it in GitHub Desktop.
Save jhorstmann/de367a42a08d8deb8df9 to your computer and use it in GitHub Desktop.
How to get the method name from a java 8 lambda using serialization hacks
package net.jhorstmann;
import java.io.*;
public class Main {
public static class SerializedLam implements Serializable {
private static final long serialVersionUID = 8025925345765570181L;
public Class<?> capturingClass;
public String functionalInterfaceClass;
public String functionalInterfaceMethodName;
public String functionalInterfaceMethodSignature;
public String implClass;
public String implMethodName;
public String implMethodSignature;
public int implMethodKind;
public String instantiatedMethodType;
public Object[] capturedArgs;
}
interface Getter<T, V> extends Serializable {
V get(T bean);
}
private static final String BINARY = "iso-8859-1";
static <T, V> String getMethodName(Getter<T, V> getter) throws IOException, ClassNotFoundException {
String originalName = java.lang.invoke.SerializedLambda.class.getName();
String replacedName = net.jhorstmann.Main.SerializedLam.class.getName();
assert (originalName.length() == replacedName.length());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(getter);
oos.flush();
byte[] bytes = new String(bos.toByteArray(), BINARY).replace(originalName, replacedName).getBytes(BINARY);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
SerializedLam serializedLambda = (SerializedLam) (in.readObject());
return serializedLambda.implMethodName;
}
static class Test {
public String rumpelstiltskin() {
return "";
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
System.out.println(getMethodName(Test::rumpelstiltskin));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment