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

问题描述 投票:2回答:1

我是使用Proxy类的最新版本。我需要为我的对象创建不可变视图的Fabric方法(MusicalInstrument.class)当我试图调用setter并且调用其他方法必须转移到我的对象时,View必须抛出一个Exception。也许你有一些我可以找到答案的例子或来源!感谢名单!

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 + '\'' +
            '}';
}
java reflection proxy-classes
1个回答
0
投票

你可以使用ImmutableProxy库的reflection-util

例:

MusicalInstrument instrument = new MusicalInstrument(1, 12.5, "Guitar");
MusicalInstrument immutableView = ImmutableProxy.create(instrument);

assertThat(immutableView.getName()).isEqualTo("Guitar");

// throws UnsupportedOperationException
immutableView.setName(…);
© www.soinside.com 2019 - 2024. All rights reserved.