title: Copy fields between similar classes in java
body: <p>I have pairs of classes where the fields of one is a subset of the fields of another and the getters of the superset classes are all predictably named (<code>getFoo()</code>).  Is there some way to <em>efficiently</em> copy all the common fields over from the superset class to the subset class, or at least auto-generate the code to do so.  </p>
  
  <p>I should note that:</p>
  
  <ul>
  <li>For various reasons, I can't edit the superset classes, nor can I just use them throughout to avoid having to do the data copy.</li>
  <li>I can potentially create new methods in the subset classes, but I can't change their fields.</li>
  <li>We have dozens of these pairs, and some of the classes have many many fields so doing this by hand is unwieldy to say the least.</li>
  <li>A colleague has come up with a method to create a generic copy method that uses java reflection to take any two classes, iterate through the fields as Strings, do string manipulation to determine the getter name, and then execute it to automatically set the field in the subset class.  It's awful, but it appears to work.  I'm really hoping there's a better way.</li>
  </ul>
  
  <p><em>Edit: some simple code as requested</em></p>
  
  <pre><code>public class SuperClass {
    private int foo;
    private int bar;
    private float bat;
    public int getFoo() { return foo; }
    public int getBar() { return bar; }
    public float getBat() { return bat; }
  }
  
  public class SubClass {
    private int foo;
    private float bat;
  }
  
  //wanted
  public static copySuperFieldsToSubMethod(Object super, Object sub) { ??? }
  
  // also acceptable would be some way to autogenerate all the assignment 
  // functions needed
  </code></pre>