JR Galia JR Galia - 11 months ago 96
Java Question

BeanUtils Copy Properties: Registering ConvertUtils

I have web application written in Java. Im using

method. If a
field is null, it throws an error. I solved it by using

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

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

Answer Source

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).