2

I'm newest at using Proxy classes. I need to create fabric method of immutable view for my object (MusicalInstrument.class) View must throw an Exception when i'm trying to invoke setter and invoking of other methods must transfer to my object. Maybe you have got some examples or sources where i can find answers! Thanx!

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 + '\'' +
            '}';
}
Serg Shapoval
  • 707
  • 1
  • 11
  • 39
  • I'll try making an example, but in the mean time, see ByteBuddy library. It has an amazing API for generating classes and can surely do what you need pretty easily. – kaqqao Nov 14 '16 at 13:01
  • i have already done it! Thanx. here you can check my code https://github.com/SergShapoval/proxyclassesexample – Serg Shapoval Nov 14 '16 at 13:33

1 Answers1

1

You can use ImmutableProxy of the reflection-util library.

Example:

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

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

// throws UnsupportedOperationException
immutableView.setName(…);
Benedikt Waldvogel
  • 12,406
  • 8
  • 49
  • 61