Last Updated: February 25, 2016
·
3.186K
· keaplogik

Java POJO without getter/setter equals/hashcode

Simple way to generate getter/setter, equals/hashcode and default constructor without ever having to own that code.

@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
public class Animal {
    @Getter @Setter private String name;
    @Getter @Setter private String gender;
    @Getter @Setter private String species;
}

Check out (Lombok)[http://projectlombok.org/] when you have time.

Oh and heres the above code without Lombok:

public class Animal {

    private String name;
    private String gender;
    private String species;

    public Animal(String name, String gender, String species) {
        this.name = name;
        this.gender = gender;
        this.species = species;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getGender(){
        return this.gender;
    }

    public void setGender(String gender){
        this.gender = gender;
    }

    public String getSpecies(){
        return this.species;
    }

    public void setSpecies(String species){
        this.species = species;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Animal)) return false;

        Animal animal = (Animal) o;

        if (gender != null ? !gender.equals(animal.gender) : animal.gender != null) return false;
        if (name != null ? !name.equals(animal.name) : animal.name != null) return false;
        if (species != null ? !species.equals(animal.species) : animal.species != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (species != null ? species.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this) //Using guava library objects toString
                .add("name", name)
                .add("gender", gender)
                .add("species", species)
                .toString();
    }
}

1 Response
Add your response

Yup! Love it!

over 1 year ago ·