It is possible to determine if a Java method reference is equivalent to another method reference. Assuming we have an interface User:
public interface User {
String firstName();
}
then we can do this:
public class Main {
public static void main(String[] args) {
print(User::firstName);
print(u -> u.firstName());
}
public interface SerializableFunction<T, R> extends Serializable, Function<T, R> {
}
private static void print(SerializableFunction<User, String> function) {
System.out.println("function = " + function);
if (Arrays.equals(serialize(function), serialize(User::firstName))) {
System.out.println("which is the method reference User::firstName");
}
}
private static byte[] serialize(SerializableFunction<User, String> function) {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
objectOutputStream.writeObject(function);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
return new byte[0];
}
}
}
This will print something like this:
function = software.chronicle.refactor.demo.serialization.Main$$Lambda$25/0x0000000800c02658@65ab7765
which is the method reference User::firstName
function = software.chronicle.refactor.demo.serialization.Main$$Lambda$33/0x0000000800c02b08@6659c656
So, it is actually possible to check if a lambda is a specific method reference.