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:
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
You could use the BeanUtils
class in the Spring Framework to do this. It may not necessarily be any more efficient than your reflection-based technique, but it's certainly simple to code. I expect that all you would need to do is:
BeanUtils.copyProperties(source, target);
Javadoc for this method is available at http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)
If that doesn't suit, you could also consider using BeanWrapper
/ BeanWrapperImpl
in the Spring Framework to iterate through the properties of your classes. That would be simpler than using low-level reflection APIs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With