Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

后端 未结 8 496
天涯浪人
天涯浪人 2020-12-05 06:57

I need to make sure that no object attribute is null and add default value in case if it is null. Is there any easy way to do this, or do I have to do it manually by checkin

8条回答
  •  遥遥无期
    2020-12-05 07:24

    Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

    return Stream.of(id, name).allMatch(Objects::isNull);
    

    This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

提交回复
热议问题