Java equals&hashcode rules check for Google AutoValue classes

Description

We use a well-known library Google AutoValue for making immutable data classes. And it uses code generation for value classes implementation.
In our case, we created a use implementation for hashCode and let AutoValue generate equals there.
Our class(some field are dropped for brevity):

@AutoValue
public abstract class Block {

  /**
   * Returns the SHA-256 hash of this block.
   */
  public abstract HashCode getBlockHash();

  public abstract long getHeight();

  @Override
  public int hashCode() {
    return getBlockHash().hashCode();
  }
}

Generated Implementation by AutoValue:

@Generated("com.google.auto.value.processor.AutoValueProcessor")
final class $AutoValue_Block extends Block {

  private final HashCode blockHash;

  private final long height;

  $AutoValue_Block(
      HashCode blockHash,
      long height) {
    if (blockHash == null) {
      throw new NullPointerException("Null blockHash");
    }
    this.blockHash = blockHash;
    this.height = height;
  }

  @Override
  public HashCode getBlockHash() {
    return blockHash;
  }

  @Override
  public long getHeight() {
    return height;
  }
  @Override
  public String toString() {
    return "Block{"
         + "blockHash=" + blockHash + ", "
         + "height=" + height + ", "
        + "}";
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof Block) {
      Block that = (Block) o;
      return this.blockHash.equals(that.getBlockHash())
          && this.height == that.getHeight());
    }
    return false;
  }
}

Actual Behaviour

Having custom implementation of equals or hashcode in AutoValue classes causes to “equals(Object obj)” and “hashCode()” should be overridden in pairs rule violation.

Expected Behaviour

The rule is not fired for AutoValue classes

Details

  • versions used: SonarCloud
  • steps to reproduce: 1) create a AutoValue class; 2) Override hashCode
  • potential workaround: exclude AutoValue classes from analysis

Full example with AutoValue usage.
Test example that verifies equals&hashcode correctness for this class using Guava’s EqualsTester.

See also

AutoValue Documentation for custom method implementations.

Hello @bullet-tooth,

Thanks for the clear description of the problem, I created a ticket (SONARJAVA-3377) to track it.
I expected that other rules would also behave poorly with Google AutoValue, but I didn’t manage to find any other problem. I’m not really familiar with this tool though…

If you face any other issue related to AutoValue, you can report them here, I will be glad to fill the ticket with more cases!

Best,
Quentin

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.