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 a3B| b1, b2, b3C| c1, c2, c3
Now I want to copy the common fields of a1, a2, a3 from B to C, is there any simple way to implement this, or is there any pattern applicable? Thanks a lot.

解决方案 »

  1.   

    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?
      

  2.   

    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. -.-"
      

  3.   

    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?
      

  4.   

    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));
    }
    }