[英]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.我得到了这个类,它对于我创建的每个实例显然都是可变的,但我想知道是否有某种包装器(或其他东西)来使这个类的一个特定对象不可变。 eg
Collections.unmodifiableList(beanList)
.例如
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;
}
}
The only way I am aware of is to instantiate it and override the methods that are able to modify the particular instance:我知道的唯一方法是实例化它并覆盖能够修改特定实例的方法:
Animal animal = new Animal("name", "commentary") {
@Override
public void setCommentary(String commentary) {
throw new UnsupportedOperationException("The Animal is immutable");
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException("The Animal is immutable");
}
};
This also satisfied the condition that only one specific instance of the class has a special behavior.这也满足了只有一个类的特定实例具有特殊行为的条件。
If you need more of them, create a wrapping class that acts as a decorator (isn't exactly).如果您需要更多它们,请创建一个充当装饰器的包装类(不完全是)。 Do not forget to make the class as
final
otherwise you would be able to override its method in the way I described above and its immutability might break.不要忘记将类设置为
final
否则您将能够以我上面描述的方式覆盖它的方法,并且它的不变性可能会中断。
Animal animal = new ImmutableAnimal(new Animal("name", "commentary"));
final class ImmutableAnimal extends Animal {
public ImmutableAnimal(Animal animal) {
super(animal.getName(), animal.getCommentary());
}
@Override
public void setCommentary(String commentary) {
throw new UnsupportedOperationException("The Animal is immutable");
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException("The Animal is immutable");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.