Skip to content

Ignored components

pawel_labaj edited this page Aug 2, 2023 · 7 revisions

If you need to have certain components in your record that should be ignored in the hashCode() and equals() calculation - they are not relevant for equality checks - AutoRecord provides an easy way to achieve this.

How to ignore a recordComponent

To ignore a recordComponent, simply add @Ignored annotation to the corresponding method in the interface.

Example interface and generated record

Here's an example interface:

@AutoRecord
interface Person {
    String name();

    int age();

    @Ignored String debugInfo();
}

Here's the corresponding generated record that demonstrates ignoring the recordComponent:

@Generated("pl.com.labaj.autorecord.AutoRecord")
@GeneratedWithAutoRecord
record PersonRecord(String name, int age, @Ignored String debugInfo) implements Person {
    PersonRecord {
        requireNonNull(name, "name must not be null");
        requireNonNull(debugInfo, "debugInfo must not be null");
    }

    @Override
    public int hashCode() {
        return hash(name, age);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (!(other instanceof PersonRecord)) {
            return false;
        }

        var otherRecord = (PersonRecord) other;
        return Objects.equals(name, otherRecord.name)
                && Objects.equals(age, otherRecord.age);
    }
}