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 (getFoo()
). Is there some way to efficiently copy all the common fields over from the superset class to the subset class, or at least auto-generate the code to do so.
I should note that:
- 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.
- I can potentially create new methods in the subset classes, but I can't change their fields.
- 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.
- 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.
Edit: some simple code as requested
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