有没有办法比较lambdas?
假设我有一个对象列表,这些对象是使用lambda表达式(闭包)定义的。有没有办法检查它们以便进行比较?
我最感兴趣的代码是
List<Strategy> strategies = getStrategies();
Strategy a = (Strategy) this::a;
if (strategies.contains(a)) { // ...
完整代码是
import java.util.Arrays;
import java.util.List;
public class ClosureEqualsMain {
interface Strategy {
void invoke(/*args*/);
default boolean equals(Object o) { // doesn't compile
return Closures.equals(this, o);
}
}
public void a() { }
public void b() { }
public void c() { }
public List<Strategy> getStrategies() {
return Arrays.asList(this::a, this::b, this::c);
}
private void testStrategies() {
List<Strategy> strategies = getStrategies();
System.out.println(strategies);
Strategy a = (Strategy) this::a;
// prints false
System.out.println("strategies.contains(this::a) is " + strategies.contains(a));
}
public static void main(String... ignored) {
new ClosureEqualsMain().testStrategies();
}
enum Closures {;
public static <Closure> boolean equals(Closure c1, Closure c2) {
// This doesn't compare the contents
// like others immutables e.g. String
return c1.equals(c2);
}
public static <Closure> int hashCode(Closure c) {
return // a hashCode which can detect duplicates for a Set<Strategy>
}
public static <Closure> String asString(Closure c) {
return // something better than Object.toString();
}
}
public String toString() {
return "my-ClosureEqualsMain";
}
}
似乎唯一的解决方案是将每个 lambda 定义为一个字段,并且只使用这些字段。如果要打印出调用的方法,最好使用 .有没有更好的 lambda 表达式方法?Method
另外,是否有可能打印lambda并获得人类可读的东西?如果您打印而不是this::a
ClosureEqualsMain$$Lambda$1/821270929@3f99bd52
得到类似的东西
ClosureEqualsMain.a()
甚至使用和方法。this.toString
my-ClosureEqualsMain.a();