Java - java.lang.NullPointerException (NPE)

Java Conceptuel Diagram

About

The 1001 way on how I get a “Null Pointer Exception

Exception in thread "main" java.lang.NullPointerException
	at com.gerardnico.biserver.Root.getB(Root.java:16)
	at com.gerardnico.biserver.Main2.main(Main2.java:29)

In general, unless otherwise noted in the javadoc, methods and constructors will throw NullPointerException if passed a null argument.

Case

Within a get function

Using jaxb, I got this kind of beans:

package com.gerardnico.npe;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlAttribute(name = "partNum")
    @XmlSchemaType(name = "unsignedInt")
    protected Long a;
    
    public long getA() {
        return a;
    }

}

It represents a XML element root with an attribute a. I got always a java.lang.NullPointerException with a simple call to the getA function. The problem comes from the fact that the function returns a long data type whereas the field is of type Long (with a Camel case).

Resolution:

  • On the class scope: Change the return data type of the function.
  • With Jaxb, adding the following global binding resolved the issue
<jaxb:globalBindings>
       <jaxb:javaType name="java.lang.Long" xmlType="xs:unsignedInt" />
</jaxb:globalBindings>







Share this page:
Follow us:
Task Runner