sixtytrees sixtytrees - 1 year ago 54
Java Question

Efficient null check for a compound object in Java

A program creates a JDialog panel with multiple tabs. One of the tabs has several tables. A JTable has adjustable column width. This tab is generated under different conditions. Sometimes from the state

, sometimes tab exists, but the
. Sometimes user haven't resized the column yet.

I am looking for a method to save the columnWidth value if user resized the column. Checking for null seems bulky in this situation:

the best method I can find is:

if( jpanel!=null &&
jpanel.jtab!=null &&
jpanel.jtab.jtable!=null && ...

Is there a better way to do this null check?

I saw this question:

is there a Java equivalent to null coalescing operator (??) in C#?

It doesn't list a solution and is quite old (Java 6-7 time). I was hoping this feature was added in later releases.

Answer Source

There's no way to do exactly what you want. However, you can just throw everything into a try statement:

try { 
    myItem = bundle.category.subcategory.item;
catch(NullpointerException ignored) {}

Note that this looks very hacked, and it's rather poor coding practice. Your current solution is probably the best approach in terms of clarity.

Edit: I tried posting another Anwser but the button is greyed out, so I'll put it here:

Feels like repeating same code many times, when you should use a for loop

You can indeed use a for loop, but that will invovle Reflection and much boilerplate code. Imagine something like this:

static boolean checkDeepNull(Object root, String... attributes) throws NoSuchFieldException, IllegalAccessException {
    Object currentAttribute = root;
    for(int attr = 0; currentAttribute != null && attr < attributes.length; attr++){
        Field nextField = currentAttribute.getClass().getField(attributes[attr]);
        Object nextAttribute = nextField.get(current);
        if(nextAttribute == null) return false;
        currentAttribute = nextAttribute;
    return true;

How to use it: if(checkDeepNull(bundle, "category", "subcategory", "item"))