Lombok - 在实现equals和hashcode时使用@Data发出警告

Krz*_*Kot 3 java jpa lombok

我有JPA实体扩展其他抽象类.我想使用@Data来避免编写setter和getter,但我的equals和hashcode方法存在.

我收到警告,但我想我不应该:

server\entity\User.java:20: warning: Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type.
@Data
^
Run Code Online (Sandbox Code Playgroud)

在我的User类中:

@Data
@Entity
public class User extends AbstractAuditingEntity implements Serializable {

    ....

    @Override
    public boolean equals(Object o) {
       ...
    }

    @Override
    public int hashCode() {
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)

当我另外将@EqualsAndHashCode(callSuper = false)添加到@Data时,我得到:

server\entity\User.java:21: warning: Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated).
@EqualsAndHashCode(callSuper = false)
Run Code Online (Sandbox Code Playgroud)

Ind*_*sak 11

@Data是一条捷径@ToString,@EqualsAndHashCode,@Getter, @Setter,和@RequiredArgsConstructor.既然你只是想@Getter@Setter,你为什么不只是使用它们(这将避免你的异常或警告消息)

@Entity
@Getter
@Setter
public class User extends AbstractAuditingEntity implements Serializable 
    ...

}
Run Code Online (Sandbox Code Playgroud)

  • 当 Lombok 遇到“@Data”注释时,它会尝试实现“equals”和“hashCode”。在 Lombok 进行二进制代码注入期间,JVM 会抱怨要修改的类中已存在“equals”和“hashCode”方法。 (2认同)
  • @KrzysztofKot你是对的,[这条评论]中的解释(/sf/ask/3238292011/#comment79495674_46261362)是错的。这是一个错误:https://github.com/rzwitserloot/lombok/issues/1078 (2认同)