简体   繁体   中英

Copying Properties from one bean into another: Java

I am facing issue in copying properties from one bean to another.

I am aware about the copyProperties() which can be used here to copy from source bean to destination bean probably if both the beans are of same type. My issue here is that I want to copy first 50 properties on the first call and next 50 properties on the second call.

Is there any way in which I can copy first 50 configs only?

You can do it only by using reflection .

@Zhuinden made a good point to start with.

To make the approach usefull for arbitrary classes, create a 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;
}

then use it like:

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;
}

Something like this would work using reflection (added an error check at the start as per 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM