samedi 22 août 2020

Given a mutable class, how to make immutable a specific object of this class?

I got THIS class which is obviously mutable for every instance I create, but I want to know if there´s some kind of wrapper (or something) to make just ONE specific object of THIS class immutable. e.g Collections.unmodifiableList(beanList).

class Animal {
    private String name;
    private String commentary;

    public Animal(String nombre, String comentario) {
        this.name = nombre;
        this.commentary = comentario;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return Objects.equals(name, animal.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    public String getName() {
        return name;
    }

    public String getCommentary() {
        return commentary;
    }

    public void setCommentary(String commentary) {
        this.commentary = commentary;
    }

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

Aucun commentaire:

Enregistrer un commentaire