说我有一个使用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();