You could use clone
. The use of this method is widely discouraged, but it does work.
For example:
public abstract class Foo implements Cloneable {
private int a;
private String b;
public Foo(int a, String b) {
this.a = a;
this.b = b;
}
public abstract void run();
public int getA() { return a; }
public String getB() { return b; }
@Override
public final Foo clone() {
try {
return (Foo) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}
}
}
Then, you can do:
Foo original = new Foo(3, "bar") {
@Override
public void run() {
System.out.println("Hello, world!");
}
};
Foo copy = original.clone();
System.out.println(copy.getA());
System.out.println(copy.getB());
copy.run();
System.out.println(copy == original);
The output is:
3
bar
Hello, world!
false
An alternative is to use Serializable
.
public abstract class Foo implements Serializable {
private int a;
private String b;
public Foo(int a, String b) {
this.a = a;
this.b = b;
}
public abstract void run();
public int getA() { return a; }
public String getB() { return b; }
public final Foo copy() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(this);
return (Foo) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
} catch (Exception e) {
throw new AssertionError();
}
}
}
With this version, replace clone
by copy
and you'll get the same result.