检测lambda是否是方法引用

时间:2016-04-25 16:12:38

标签: java lambda

有没有办法确定给定的Java lambda对象是方法引用还是" CallSite特定的"拉姆达:

boolean isMethodReference(Object lambda)

正面例子:

assertTrue(isMethodReference(Object::toString));

" CallSite特定"的否定示例拉姆达:

long valueFromCallSite = System.currentTimeMillis();
Consumer<Object> lambda = o -> {
    if (valueFromCallSite % 2 == 0) {
        o.toString();
    } else {
        o.hashCode();
    }
};
assertFalse(isMethodReference(lambda));

1 个答案:

答案 0 :(得分:0)

可以确定一个 Java 方法引用是否等同于另一个方法引用。假设我们有一个接口 User:

public interface User {
    String firstName();
}

然后我们可以这样做:

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];
    }
}

}

这将打印如下内容:

function = software.chronicle.refactor.demo.serialization.Main$$Lambda$25/0x0000000800c02658@65ab7765

这是方法引用 User::firstName

function = software.chronicle.refactor.demo.serialization.Main$$Lambda$33/0x0000000800c02b08@6659c656

因此,实际上可以检查 lambda 是否是特定的方法引用。