使用代理类创建对象的不可变视图



我是最新的使用代理类。我需要为我的对象(musicalinstrument。class)创建不可变视图的结构方法当我试图调用setter和调用其他方法时,视图必须抛出一个异常,必须转移到我的对象。也许你有一些例子或来源,我可以找到答案!谢谢!

public class MusicalInstrument implements Serializable {
/**
 * ID of instrument.
 */
private int idInstrument;
/**
 * Price of instrument.
 */
private double price;
/**
 * Name of instrument.
 */
private String name;

public MusicalInstrument() {
}
public MusicalInstrument(int idInstrument, double price, String name) {
    this.idInstrument = idInstrument;
    this.price = price;
    this.name = name;
}

public int getIdInstrument() {
    return idInstrument;
}
public void setIdInstrument(int idInstrument) {
    this.idInstrument = idInstrument;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    MusicalInstrument that = (MusicalInstrument) o;
    if (idInstrument != that.idInstrument) return false;
    if (Double.compare(that.price, price) != 0) return false;
    return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
    int result;
    long temp;
    result = idInstrument;
    temp = Double.doubleToLongBits(price);
    result = 31 * result + (int) (temp ^ (temp >>> 32));
    result = 31 * result + (name != null ? name.hashCode() : 0);
    return result;
}
@Override
public String toString() {
    return "MusicalInstrument{" +
            "idInstrument=" + idInstrument +
            ", price=" + price +
            ", name='" + name + ''' +
            '}';
}

您可以使用reflection-util库的ImmutableProxy

的例子:

MusicalInstrument instrument = new MusicalInstrument(1, 12.5, "Guitar");
MusicalInstrument immutableView = ImmutableProxy.create(instrument);
assertThat(immutableView.getName()).isEqualTo("Guitar");
// throws UnsupportedOperationException
immutableView.setName(…);

相关内容

  • 没有找到相关文章

最新更新