猜测 equals() 中使用的运行时字段
是否可以在运行时以编程方式猜测哪些字段是 由我不拥有的对象的 equals() 方法使用?尤其是当 equals() 不使用 getters 来访问字段:
class OverrideEquals {
String firstField;
Integer secondField = 0;
@Override public boolean equals(Object other) {
if ( other instanceof OverrideEquals ) {
return lastField.equals(((OverrideEquals) other).lastField);
}
return false;
}
}
在这个示例中,有没有办法知道 equals() 在调用时使用firstField而不是lastField(字节码分析、代理...)?
Is it possible to guess programmatically at runtime which fields are
used by equals() method of an object I don't own ? Especially when
getters are not used by equals() to access fields :
class OverrideEquals {
String firstField;
Integer secondField = 0;
@Override public boolean equals(Object other) {
if ( other instanceof OverrideEquals ) {
return lastField.equals(((OverrideEquals) other).lastField);
}
return false;
}
}
In this example, is there a way to know equals() uses firstField and not lastField (byte-code analysis, proxy,...) at the moment it is invoked ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
反编译字节码会给你这个答案,但更简单、更合乎逻辑的方法是要求代码所有者以某种方式注释他们的
equals
方法,例如@ChecksForEqualityOn(. ..)
。您需要在运行时执行此操作是否有特殊原因?
Decompiling the bytecode would give you that answer, but an easier and more logical way to do it would be to ask the code owner to annotate their
equals
method in some way, e.g.@ChecksForEqualityOn(...)
.Is there a particular reason you need to do this at runtime?