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.