简体   繁体   中英

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 ? 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 ?

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(...) .

Is there a particular reason you need to do this at runtime?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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