Java - java.lang.NullPointerException (NPE)

> Procedural Languages > Java

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

3 - Case

3.1 - 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>
Advertising
lang/java/npe.txt · Last modified: 2017/05/29 17:06 by gerardnico