-1

I get an error A "NullPointerException" could be thrown; "entity" is nullable here. below is a sample of my code.

NewResponse newResponse = new NewResponse();
if(entity.getName() != null){
        GetDetails response = crossService
            .getDetails(entity.getName());

        response.setHumanName(response.getFullName());
        }

Is there a way that I can fix null pointer dereference?

newbie
  • 101
  • 2
  • 4
  • 8

1 Answers1

-1

Firstly, the entity object can be null. You are not doing any null check for entity. You can do that by if(null! =entity). Secondly, you are doing entity.get operations, this operation can throw a null pointer exception as well. Thus we need a null check here as well. So conbined together you can do like

if (null! =entity && null! = entity.getName()) {

//Do your stuff here.

}

By doing this check you will not get a null pointer warning as well as null pointer exception. Alternatively uf you are using java 8 then you can use an "optional" for the same. Which is a more cleaner way for avoiding null pointers.

elPolloLoco
  • 291
  • 1
  • 8
CodeMaster
  • 171
  • 15