Overriding the java equals() method - not working?

后端 未结 8 1253
花落未央
花落未央 2020-11-22 02:33

I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:02

    Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;

    import lombok.EqualsAndHashCode;
    
    @EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
    public class ErrorMessage{
    
        private long        errorNumber;
        private int         numberOfParameters;
        private Level       loggingLevel;
        private String      messageCode;
    

    See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:

    
        org.projectlombok
        lombok
        1.14.8
        provided
    
    

提交回复
热议问题