简体   繁体   中英

Ignore properties in subclass with BeanUtils

I´m usign Spring BeanUtils with this class structure

     class B{
          int b;
     }

     class A{
           int a;
           B bClass;
     }

Then receiving a instance A want to create a new one but without the value of Bb So I´m doing this:

  A a = new A();
  B b = new B();
  b.setb(2);
  a.seta(1);
  a.setbClass(b);
  A a1 = new A();
  BeanUtils.copyProperties(a, a1, new String[]{"bClass.b"});

But still the value of b attribute 2 is still coping on the a1 class.

What I´m doing wrong

BeanUtils.copyProperties simply copies field values. If it is a reference field it will copy it too (if it's not in ignoreProperties), it does not make deep copying. You cannot make it ignore B's fields.

BeanUtils.copyProperties() is intended for shallow copies, so you can't use it for nested fields. You could try with BeanWrapper , but I'm not sure there is something like ignored properties there, you might have to do it manually.

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