Skip to content

Instantly share code, notes, and snippets.

@dgageot
Created August 19, 2014 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgageot/e099e4e9a4becca06e18 to your computer and use it in GitHub Desktop.
Save dgageot/e099e4e9a4becca06e18 to your computer and use it in GitHub Desktop.
Find Lambda parameter types with serialization. Works only on serializable lambda
package avaj.lang.invoke;
import java.io.*;
import java.lang.invoke.SerializedLambda;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
public class FindParametersTypes {
public static void main(String[] args) throws Exception {
System.out.println(getMethodSignature((String s) -> s));
}
static <T, R> String getMethodSignature(MyFunction<T, R> lambda) throws Exception {
String serializedLambdaName = SerializedLambda.class.getName();
String replacementName = SerializedLamdb2.class.getName();
byte[] serialized;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(lambda);
serialized = bos.toByteArray();
}
SerializedLamdb2 lamdbaDescription;
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(new String(serialized, ISO_8859_1).replace(serializedLambdaName, replacementName).getBytes(ISO_8859_1)))) {
lamdbaDescription = (SerializedLamdb2) in.readObject();
}
return lamdbaDescription.implMethodSignature;
}
@FunctionalInterface
static interface MyFunction<T, R> extends Serializable {
R apply(T t);
}
}
package avaj.lang.invoke;
import java.io.Serializable;
public class SerializedLamdb2 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment