您的位置:首页 > 移动开发

copvalue from wrapper type to primitive type

2016-06-18 09:18 211 查看
/**
* <pre>
* if the field of orig is wrapper, will skip it and would not copy it to dest.
* in the meantime, the primitive filed should default value when dest object corresponding wrapper field value is null;
* </pre>
*
* @param dest
* @param orig
*/
void copyProperties(Object dest, Object orig) {

Field[] fields = orig.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
Class<?> fieldType = field.getType();
String fieldName = field.getName();
Object fieldValue = field.get(orig);

// skip "orig" object's field that it's wrapper type and null;
// and  "dest" object's field that it's primitive type should be the default value automatically when "orig" object's filed value null;
if (ClassUtils.isPrimitiveWrapper(fieldType) && fieldValue == null) {
continue;
}

BeanUtils.copyProperty(dest, fieldName, fieldValue);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
}
}


result test:

@Test
public void test01() throws InvocationTargetException, IllegalAccessException {

Product02 product02 = new Product02();
product02.setName("name02");
product02.setProduct_int(123);
product02.setProduct_double(4.56);
product02.setPrice(new Amount("product type1111", new BigDecimal(2681)));

Product01 product01 = new Product01();

System.out.println(product02);
copyProperties(product01, product02);
//BeanUtils.copyProperties(product01, product02);
System.out.println(product01);

}


Product02{name='name02', product_int=123, product_double=4.56, product_boolean=null, product_char=null, product_byte=null, product_long=null, price=Amount{productTpye='product type1111', price=2681}}

Product01{name='name02', product_int=123, product_double=4.56, product_boolean=false, product_char= , product_byte=0, product_long=0, product_float=0.0, price=Amount{productTpye='product type1111', price=2681}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java