假设我有一个 List 对象,它是使用 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 定义为一个字段,并且只使用这些字段。如果想打印出调用的方法,最好使用 Method
。有没有更好的 Lambda 表达式?
此外,是否有可能打印一个 lambda 并得到一些人类可读的东西? 如果你打印 this::a
而不是
ClosureEqualsMain$$Lambda$1/821270929@3f99bd52
比如
ClosureEqualsMain.a()
甚至使用 this.toString
和方法。
my-ClosureEqualsMain.a();