Skip to content

Ignored components

pawel_labaj edited this page Jul 20, 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 component

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

Example interface and generated record

Here's an example interface:

import pl.com.labaj.autorecord.AutoRecord;
import pl.com.labaj.autorecord.Ignored;

@AutoRecord
interface Person {
    String name();

    int age();

    @Ignored String debugInfo();
}

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

import pl.com.labaj.autorecord.GeneratedWithAutoRecord;
import pl.com.labaj.autorecord.Ignored;
import javax.annotation.processing.Generated;
import java.util.Objects;

import static java.util.Objects.hash;
import static java.util.Objects.requireNonNull;

@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);
    }
}
Clone this wiki locally