↓ Skip to main content

NullPointerException when accessing primitive fields using reflection

·233 words·2 mins

I’ve longed to write this article quite a long time ago, but I have not had a good example for it. Today I have it :)

I have mapped a pojo in iBATIS:


public class Shop {

    private int id;

    private String name;

    private String addressLine;
    
    private String city;
    
    private String phones;
    
    private ShopNetwork network;
    
    private int map;

map is an optional parameter, i.e. in the database its value may be null. As far as I remember, the early versions of Hibernate in this case would safely replace null with 0 in the pojo, in case of a primitive field. For certain circumstances this is not bad at all. However the correct solution is to have a field of non-primitive type wrapper, like Integer, so that null would remain null.

This time I was “surprised” by iBATIS throwing an NPE. The stack (largely abridged) was very strange:


com.ibatis.common.jdbc.exception.NestedSQLException:   
--- The error occurred in com/anydoby/catalog/dao/pojo/enums.xml.  
--- The error occurred while applying a result map.  
--- Check the enums.shopWithNetwork.  
--- The error happened while setting a property on the result object.  
--- Cause: net.sf.cglib.beans.BulkBeanException
....
net.sf.cglib.beans.BulkBeanException
    com.anydoby.catalog.dao.pojo.Shop$$BulkBeanByCGLIB$$4d784893.
setPropertyValues(<generated>)
....
java.lang.NullPointerException
    com.anydoby.catalog.dao.pojo.Shop$$BulkBeanByCGLIB$$4d784893.
setPropertyValues(<generated>)

If I hadn’t longed to write this article long ago, I would have had quite hard time chasing the bug, but today I just replaced int with Integer and everything works nice again :)


First published on the old anydoby.com blog on 2007-08-22.