我在将属性从一个bean复制到另一个bean时面临问题。
我知道copyProperties()
可以在这里用于从源bean复制到目标bean,如果两个bean是相同类型的话。我这里的问题是,我想在第一次调用时复制前50个属性,在第二次调用时复制后50个属性。
是否有任何方法可以只复制前50个配置?
只能使用reflection
。
@Zhuinden开头说得很好。
要使该方法对任意类有用,请创建一个Map name -> field
:
Map<String,Field> asMap( Field[] fields ){
Map<String,Field> m = new HashMap<String,Field>();
for( Field f : fields ){
f.setAccessible( true );
m.put( f.getName(), f );
}
return m;
}
然后像这样使用:
Map<String,Field> trg = asMap( target.getClass().getDeclaredFields() );
int counter = 50;
for( Field f : Source.getClass().getDeclaredFields() ){
f.setAccessible( true );
Field fieldTarget = trg.get( f.getName() );
if( null != fieldTarget ){
fieldTarget.set(target, f.get(source));
counter--;
}
if( 0 == counter ) break;
}
使用反射(在开始时根据https://stackoverflow.com/a/3738954/2413303添加错误检查)可以这样工作:
if(source.getClass() != target.getClass())
{
throw new RuntimeException("The target and source classes don't match!");
}
Field[] fieldSources = source.getClass().getDeclaredFields();
Arrays.sort(fieldSources);
Field[] fieldTargets = target.getClass().getDeclaredFields();
Arrays.sort(fieldTargets);
//source and target class is the same so their fields length is the same
for(int i = 50*n; i < fieldSources.length && i < 50*n+50; i++)
{
Field fieldSource = fieldSources[i];
Field fieldTarget = fieldTargets[i];
fieldSource.setAccessible(true);
fieldTarget.setAccessible(true);
fieldTarget.set(target, fieldSource.get(source));
}