How to check if object and nested fields are null [duplicate]

*爱你&永不变心* 提交于 2020-07-16 04:04:32

问题


I have an object and i want to check if this object or nested fields are null. I want to print this neted field, but i should check if there is null in some level, otherwise i will get null pointer exception .

I know i can do this:

if( object != null && object.A != null && object.A.B != null && object.A.B.C != null && object.A.B.C.D != null) { doSomething( object.A.B.C.D);}

but its so long. Do you know better way to check it ?


回答1:


Optional is a good way in Java 8.

String value = foo.getBar().getBaz().toString();

With optional it will be:

String value = Optional.ofNullable(foo)
                       .map(Foo::getBar)
                       .map(Bar::getBaz)
                       .map(Baz::toString)
                       .orElse("EmptyString");



回答2:


You could implement an interface on all objects with method that returns all child objects and create a method that calls itself recursively to verify that all objects are set.




回答3:


Let assume that this is a check to prevent misuse of a method, so this should not occurs too many time.

Simply catch this exception, this will invalidate the value.

private boolean isValid(YourObject object){
    try{
         return object.A.B.C.D != null;
    } catch (NullPointerException npe){
        return false;
    }
}

Of course, don't use this solution if you are doing a lot of validation and those return false to often, exception are an heavy process.

EDIT :

As Fildor point it out, there is a cost to use a try-catch even without exception. But using this answer I can assume this will be limited and there is not much optimization to do on this unique line.



来源:https://stackoverflow.com/questions/42856818/how-to-check-if-object-and-nested-fields-are-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!