Copying fields between classes in Java
I have a pair of classes. The field of one class is a subset of the field of the other. The getters of superset classes can be named in advance (getfoo()) Is there any way to effectively copy all common fields from superset classes to subset classes, or at least automatically generate code
I should note that:
>For various reasons, I cannot edit superset classes, nor can I just use them to avoid data copying. > I can create new methods in subset classes, but I can't change their fields. > We have dozens of such pairs. Some classes have many fields, so it is clumsy to do this by hand. > A colleague proposed a method to create a general replication method, which uses java reflection to accept any two classes, iterates the string through the field, performs string operation to determine the getter name, and then executes it to automatically set the field in the subclass It's terrible, but it seems to work I really hope there is a better way
Edit: some simple code requirements
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
Solution
You can use the bean utils class in the spring framework to do this It may not necessarily be more effective than reflection - based techniques, but the code is simple I expect all you need to do is:
BeanUtils.copyProperties(source,target);
The Javadoc of this method can be found in http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties (java.lang.object,% 20java. Lang.Object)
If not, you can also consider using beanwrapper / beanwrapperimpl in the spring framework to traverse the properties of the class This will be simpler than using a low - level reflection API