Re: AspectJ: solution to Java's repetitiveness?
On Apr 19, 8:05 pm, Mark Space <marksp...@sbc.global.net> wrote:
Even C++ creates copy constructors with this semantics for you.
Er, that's what Java's .clone() method does by default.
I'm afraid it doesn't have the right semantics. I wrote a test
application to check this. Suppose I want a tree of 3D vectors. I also
want to be able to copy these trees so that I can modify the original
with impunity:
public class Vec3D implements Cloneable {
double x, y, z;
}
import java.util.ArrayList;
public class Vec3DTree implements Cloneable {
Vec3D leaf;
ArrayList<Vec3DTree> branches;
Vec3DTree() { // trivial default CTOR - more repetitiveness
leaf = new Vec3D();
branches = new ArrayList<Vec3DTree>();
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Vec3DTreeMain {
public static void main(String[] args) {
Vec3DTree t1 = new Vec3DTree();
t1.leaf.x = 1;
t1.branches.add(new Vec3DTree());
t1.branches.get(0).leaf.y = 2;
try {
Vec3DTree t2 = (Vec3DTree) t1.clone();
// modify original
t1.branches.get(0).leaf.z = 3;
}
catch(CloneNotSupportedException e) {
System.out.println("oops");
}
}
}
The line that modifies the original in the try block also modifies the
"copy". So, Object::clone didn't clone the branches. I probably have
to write stuff by hand, like overriding Object::clone in Vec3D and
perhaps subclassing ArrayList and overriding Object::clone there as
well.
Consider this equivalent C++ that however does have the right copying
semantics:
#include <vector>
struct Vec3D {
double x, y, z;
Vec3D() { x = y = z = 0; }
};
template<typename T>
struct Tree {
T leaf;
std::vector<Tree<T> > branches;
};
typedef Tree<Vec3D> Vec3DTree;
int main() {
Vec3DTree t1; // default CTOR
t1.leaf.x = 1;
t1.branches.push_back(Vec3DTree());
t1.branches[0].leaf.y = 2;
Vec3DTree t2 = t1; // copy CTOR
t1.branches[0].leaf.z = 3; // modify original
}