Java 使用代理类创建对象的不可变视图
我最不擅长使用代理类。我需要为我的对象(MusicalInstrument.class)创建不可变视图的结构方法 当我试图调用setter时,视图必须抛出异常,其他方法的调用必须转移到我的对象。 也许你有一些例子或来源,我可以找到答案!塔克斯Java 使用代理类创建对象的不可变视图,java,reflection,proxy-classes,Java,Reflection,Proxy Classes,我最不擅长使用代理类。我需要为我的对象(MusicalInstrument.class)创建不可变视图的结构方法 当我试图调用setter时,视图必须抛出异常,其他方法的调用必须转移到我的对象。 也许你有一些例子或来源,我可以找到答案!塔克斯 public class MusicalInstrument implements Serializable { /** * ID of instrument. */ private int idInstrument; /** * Price o
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 + '\'' +
'}';
}
您可以使用库的
ImmutableProxy
例如:
MusicalInstrument instrument=新的MusicalInstrument(1,12.5,“吉他”);
MusicalInstrument immutableView=ImmutableProxy.create(乐器);
断言(immutableView.getName()).isEqualTo(“吉他”);
//抛出不支持的操作异常
immutableView.setName(…);
我将尝试制作一个示例,但同时请参阅ByteBuddy库。它有一个惊人的API来生成类,当然可以很容易地做你需要的事情。我已经做了!塔克斯。在这里你可以检查我的代码