简体   繁体   English

猜猜equals()中使用的运行时字段

[英]Guess at runtime fields used in equals()

Is it possible to guess programmatically at runtime which fields are used by equals() method of an object I don't own ? 是否可以在运行时以编程方式猜测我不拥有的对象的equals()方法使用的字段? Especially when getters are not used by equals() to access fields : 尤其是当equals()不使用getter来访问字段时:

    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 ? 在此示例中,有没有办法知道equals()在被调用时立即使用firstField而不使用lastField(字节码分析,代理等)?

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, eg @ChecksForEqualityOn(...) . 反编译字节码将为您提供答案,但是更简单,更合理的方法是让代码所有者以某种方式注释其equals方法,例如@ChecksForEqualityOn(...)

Is there a particular reason you need to do this at runtime? 您是否需要在运行时执行此操作的特定原因?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM