JR Galia JR Galia - 5 days ago 7
Java Question

BeanUtils Copy Properties: Registering ConvertUtils

I have web application written in Java. Im using

BeanUtils.copyProperties
method. If a
date
field is null, it throws an error. I solved it by using
ConvertUtils.register
method.

ConvertUtils.register(new DateConverter(null), Date.class);


It works now, but what is the correct way of using
ConvertUtils.register
. Where should it be placed?

Answer

What you have done is CORRECT for only one class(Date) type. This is achieved for all the supported types including Date by calling register method on ConvertUtilsBean as below:

    ConvertUtilsBean convertUtilsBean = BeanUtilsBean.getInstance().getConvertUtils();
    convertUtilsBean.register(false, true, -1);

Here, first argument false means don't throw conversion exception. Second argument true represents, if there is exception, use null as default value. Third argument -1 represent that array types will be defaulted to null. If you want to default arrays with specific size, mention the size as third parameter.

Refer more details here (ConvertUtilsBean Javadoc).