Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask BeanUtils to ignore null values

Using Commons beanUtils I would like to know how to ask any converter say the Dateconverter to ignore null values and use null as default. As an example consider a public class,

public class X {
    private Date date1;
    private String string1;
    //add public getters and setters
}

and my convertertest as,

public class Apache {

    @Test
    public void testSimple() throws Exception {
        X x1 = new X(), x2 = new X();
        x1.setString1("X");
        x1.setDate1(null);
        org.apache.commons.beanutils.BeanUtils.copyProperties(x2, x1);
        //throws ConversionException
        System.out.println(x2.getString1());
        System.out.println(x2.getDate1());
    }
}

The above throws a NPE since the date happens to be null. This looks a very primitive scenario to me which should be handled by default (as in, I would expect x2 to have null value for date1). The doco tells me that I can ask the converter to do this. Can someone point me as to the best way for doing this ?

I dont want to get hold of the Converter and isUseDefault() to be true because then I have to do it for all Date, Enum and many other converters !

like image 217
Kannan Ekanath Avatar asked Apr 08 '10 15:04

Kannan Ekanath


4 Answers

Apparently it looks like, there is a way to tell the ConvertUtils to not throw exceptions on null values which is achieved by calling

BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
like image 69
Kannan Ekanath Avatar answered Nov 08 '22 09:11

Kannan Ekanath


The best solution is update to BeanUtils 1.9.0, since this problem is fixed as you can see here https://issues.apache.org/jira/browse/BEANUTILS-454

like image 24
Diego Plentz Avatar answered Nov 08 '22 11:11

Diego Plentz


Maybe a little late but looks that you can register a DateConverter https://issues.apache.org/jira/browse/BEANUTILS-387

like image 2
Ninju Bohra Avatar answered Nov 08 '22 11:11

Ninju Bohra


I recently ran into this issue and just converted my variable to a string to avoid this error and converted it back to a date when needed. Not the most elegant solution, but for simplicity and to avoid problems like this, it's a viable solution. The other caveat was that BeanUtils would fire off it's methods before my classes would load, so I opted for this rather than a more complicated solution to the problem using custom classloaders.

By the way, prior to verion 1.8.0, BeanUtils itself would ignore these null values.

See this link: No value specified for 'Date' when the field is a java.util.Date with a null value for a detailed explanation.

like image 1
James Drinkard Avatar answered Nov 08 '22 09:11

James Drinkard