如果我为一个类动态覆盖equals
和hashCode
方法,调用这些方法直接调用覆盖的版本,但将它们用于 set 使用非覆盖版本。为什么会这样,是否仍然可以为所有用法动态覆盖这两种方法?
class SuperClass {
public boolean equals(Object other) {
println 'non overridden equals called'
false
}
public int hashCode() {
println 'non overridden hashCode called'
1
}
}
SuperClass.metaClass.equals = { Object other ->
println 'overridden equals called'
true
}
SuperClass.metaClass.hashCode = { ->
println 'overridden hashCode called'
1
}
def a = new SuperClass()
def b = new SuperClass()
println a.hashCode() // overriden hashCode called
println b.hashCode() // overriden hashCode called
println a.equals(b) // overriden equals called
println([a, b].toSet().size()) // non overriden methods called, returns 2 instead of 1