Skip to content
Advertisement

How check if an Attribute(object) is null in Java

I need specific data for a report, then I gettin all information from a parent object

Object1

It has many attributes, object attributes

Object11, Object12, Object13, attr1, attr2...

The attributes has many attributes too

Object111, Object131, Object132,..

by now I got 5 level data attributes.

When I send information to my report it says, Error: cause:null

object1.getIdObject11().getIdObject111().getDescription;

It trows error because Object111 is null

I tried using

object1.getIdObject11().getIdObject111().getDescription==null?'':object1.getIdObject11().getIdObject111().getDescription;

but it only verify if description is null, and throws the same error Then I tried to verify Object

if(object1.getIdObject11().getIdObject111() == null) {
    var = object1.getIdObject11().getIdObject111().getDescription;
} else {
    var = "";
}

But when Object11 is null, it throws same error.

I don’t think its a good way doing this for each attribute (have to get like 30 attributes)

if(object1.getIdObject11()!=null) {
    if(object1.getIdObject11().getIdObject111()!=null) {
        if(object1.getIdObject11().getIdObject111().getIdObject1111()!=null) {
             //...
         }
    }
}

I want to verify if is there a null object and set ” (blank) if it is, with no such a large code(because the gotten params are set inside a report, mixed with letter).

reportline1 = "Area: "+object1.getIdObject11().getIdObject111().getName;

Advertisement

Answer

You code breaks Demeter’s law. That’s why it’s better to refactor the design itself. As a workaround, you can use Optional

   var = Optional.ofNullable(object1)
    .map(o -> o.getIdObject11())
    .map(o -> o.getIdObject111())
    .map(o -> o.getDescription())
    .orElse("")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement