我有一对类,其中一个的字段是另一个字段的子集,超集类的getter都是可预测的名字(getFoo()).有没有办法有效地将所有公共字段从超集类复制到子集类,或者至少自动生成代码来执行此操作.
我应该注意到:
编辑:一些简单的代码请求
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
Run Code Online (Sandbox Code Playgroud)
gut*_*tch 13
您可以使用BeanUtilsSpring Framework中的类来执行此操作.它可能不一定比基于反射的技术更有效,但编码肯定很简单.我希望您需要做的就是:
BeanUtils.copyProperties(source, target);
Run Code Online (Sandbox Code Playgroud)
这个方法的Javadoc可以在 http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)
如果这不合适,您还可以考虑在Spring Framework中使用BeanWrapper/ BeanWrapperImpl来迭代类的属性.这比使用低级反射API更简单.
| 归档时间: |
|
| 查看次数: |
9922 次 |
| 最近记录: |