Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javabeans - BeanUtils converting java.util.Map to nested bean

I have a Java bean which has a field which in turn is another bean

public class BeanOne {
   private String fieldOne;
   private BeanTwo fieldTwo;

   public String getFieldOne() {return this.fieldOne;}  
   public void setFieldOne(String fieldOne){this.fieldOne = fieldOne}

   public BeanTwo getFieldTwo() {return this.fieldTwo;}  
   public void setFieldTwo(BeanTwo fieldTwo){this.fieldTwo = fieldTwo}
}

public class BeanTwo {
   private String fieldOne;

   public String getFieldOne() {return this.fieldOne;}  
   public void setFieldOne(String fieldOne){this.fieldOne = fieldOne}
}

I am trying to pass a map to BeanUtils to try and convert the following map into BeanOne

Map beanOneMap = new HashMap<String, Object>();
beanOneMap.put("fieldOne", "fieldOneValue");
Map beanTwoMap = new HashMap<String, Object>();
beanTwoMap.put("fieldOne", "fieldOneValue");
beanOneMap.put("fieldTwo", beanTwoMap);

BeanOne beanOne = new BeanOne();
BeanUtils.populate(beanOne, beanOneMap);

But it throws an error saying - Cannot invoke BeanOne.setFieldTwo on bean class 'class Bean' - argument type mismatch - had objects of type "java.util.HashMap" but expected signature "BeanTwo"

How can I use BeanUtils to correctly populate the inner bean ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use Spring's BeanWrapper class. It supports nested properties, and optionally create inner beans for you:

BeanOne one = new BeanOne();
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(one);
wrapper.setAutoGrowNestedPaths(true);

Map<String, Object> map = new HashMap<>();
map.put("fieldOne", "fieldOneValue");
map.put("fieldTwo.fieldOne", "fieldOneValue");

wrapper.setPropertyValues(map);

assertEquals("fieldOneValue", one.getFieldOne());
BeanTwo two = one.getFieldTwo();
assertNotNull(two);
assertEquals("fieldOneValue", two.getFieldOne();

The killer feature of auto-creating inner beans is achieved thanks to wrapper.setAutoGrowNestedPaths(true). The default value is false, which means you will get a NullValueInNestedPathException if an element in the property path is null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...