Copy common fields/values in super class
Sorry that I don't have Chinese input here.I have a super class A, and children classes B and C. All of them have their own fields.
A| public a1, public a2, public a3
B| b1, b2, b3
C| c1, c2, c3
Now I want to copy the common fields of a1, a2, a3 from B to C, is there any 易做图 way to implement this, or is there any pattern applicable? Thanks a lot.
[img=http://www.coderanch.com/upload/2012/2/29/73ba4377039c5002ff88cd9b472d8d81_159348.png__thumb][/img] --------------------编程问答-------------------- why do you want to copy the common fields of a1, a2, a3 from B to C?
C has had the common fields of a1, a2, a3.
you mean you want to copy the fields of b1, b2, b3? --------------------编程问答-------------------- --------------------编程问答-------------------- sorry, I should say I have an object of B, and try to copy the common fields in this object to an object of C. -.-" --------------------编程问答-------------------- Previously, I tried to add a copy(A source) method in A, and copy each field one by one. However, since A contains quite a lot of fields, I am wondering if this can be done in a CLONE way rather than copy each field one by one? --------------------编程问答--------------------
public void copy(B b) throws IllegalArgumentException, SecurityException,
IllegalAccessException, NoSuchFieldException {
String[] names = new String[] { "a1", "a2", "a3" };
for (int i = 0; i <= names.length - 1; i++) {
this.getClass().getField(names[i])
.set(this, b.getClass().getField(names[i]).get(b));
}
}
补充:Java , Java SE