3

Is there any shortcut for checking if an objects all elements(and also their elements) are null. For example I want to check If a country object(and its city and its street) is null or not? I don't want to check them one by one like;

country == null || country.city == null || country.city.street == null


public class Country{

  City city;
  ....

}

public class City{

  Street street;
  ....
}

public class Street{
  ....
}
MarmiK
  • 5,639
  • 6
  • 40
  • 49
hellzone
  • 5,393
  • 25
  • 82
  • 148

1 Answers1

1

There is no shortcut: you have to browse recursively your instances and check their fields. You could use a custom version of the browser shown in How to list all properties exposed by a Java class and its ancestors in Eclipse?. Anyway that approach would make sense if you are working with esoteric legacy code, whereas if you are writing new classes is better enforce all not-nulls in constructor of factory methods.

Community
  • 1
  • 1
robermann
  • 1,722
  • 10
  • 19
  • You have to browse recursively? I'd think when you have to do that, the answer is already clear - not all contained references are null. – Ingo Mar 07 '14 at 11:56
  • they could be null on the second level, and so on :) – robermann Mar 07 '14 at 12:47
  • 1
    But then the object you started with must have had at least one non-null reference, and so the check can return false. – Ingo Mar 07 '14 at 12:55