什么是在Java中检查对象及其成员是否为空的最佳方法

huangapple go评论78阅读模式
英文:

What is the best way to check object and it's members are null in Java

问题

这段代码如下:

类 X {
    Map< Y, Z> 从名称到Z对象的映射;
}

我想检查 X 和该映射是否为空。
目前我有以下代码:

private void checkFunction(X x) {
    if (x == null || x.getMap().isEmpty()) { 
        throw new Exception("某些异常信息");
    }
}

想知道是否有更优雅的方式来进行检查。

英文:

Have this piece of code:

Class X {
    Map&lt; Y, Z&gt; mapFromNameToZObjects;
}

I want to check if X and the map are null.
Currently I have the following:

private checkFunction(X x) {
  If (x == null || x.getMap.isNullOrEmpty) { 
      throw some Exception
   }
}

Wondering if there is a prettier way to check it.

答案1

得分: 2

你可以在其中使用Optionalfiltermap方法:

private void checkFunction(X x) throws Exception {
    Optional.ofNullable(x)
            .map(X::getMap)
            .filter(map -> !map.isEmpty())
            .orElseThrow(() -> new Exception()); // 在此处添加您的异常

  //...
}
英文:

You could use Optional with it's filter and map methods :

private void checkFunction(X x) throws Exception {
    Optional.ofNullable(x)
            .map(X::getMap)
            .filter(map -&gt; !map.isEmpty())
            .orElseThrow(() -&gt; new Exception()); // your exception here

  //...
}

答案2

得分: 1

使用 Optional.ofNullable()Optional.map()

public static class X<K, V>{
    Map<K, V> mapFromNameToZObjects;
    public Map<K, V> getMap() {
        return mapFromNameToZObjects;
    }
}

public static void main(String[] args) {
    X<String, String> x = new X<>();
    
    Optional<Map<String, String>> optionalMap = Optional.ofNullable(x).map(X::getMap);
    
    boolean allNull = !(optionalMap.isPresent());
}
英文:

By using Optional.ofNullable() and Optional.map()

public static class X&lt;K, V&gt;{
    Map&lt;K, V&gt; mapFromNameToZObjects;
    public Map&lt;K, V&gt; getMap() {
        return mapFromNameToZObjects;
    }
}

public static void main(String[] args) {
    X&lt;String, String&gt; x = new X&lt;&gt;();
    
    Optional&lt;Map&lt;String, String&gt;&gt; optionalMap = Optional.ofNullable(x).map(X::getMap);
    
    boolean allNull = !(optionalMap.isPresent());
}

答案3

得分: 0

如果你想自己编写代码。

if (x == null || x.isEmpty())

如果已经在使用apache collections库

if (MapUtils.isEmpty(x))

英文:

If you want to code it yourself.

if (x == null || x.isEmpty())

If already using the apache collections library.

if (MapUtils.isEmpty(x))

答案4

得分: 0

如果对象为null,则它没有任何成员,因此对象及其成员不能同时为null。

如果您想要检查对象或其字段是否为null,则可以使用:

    if (x == null || x.getMap() == null) {
        // 抛出异常
    }

如果您还想检查其映射是否为空(即它不包含任何键值映射),则可以使用:

    if (x == null || x.getMap() == null || x.getMap().isEmpty()) {
        // 抛出异常
    }
英文:

If the object is null then it doesn't have any members, so you cannot have the object and its members null at the same time.

If you want to check if either the object or its field is null then you can use:

    if (x == null || x.getMap() == null) {
        // throw exception
    }

If you want to also check its map is empty(it doesn't contain any key-value mappings) then you can use:

    if (x == null || x.getMap() == null || x.getMap().isEmpty()) {
        // throw exception
    }

答案5

得分: -2

最简单的检查方法是 entity == null。没有比这更简短的方法。

注意,标准库中有一个用于此目的的方法:

Objects.isNull(Object obj)

还有另一个与上述方法相反的方法:

Objects.nonNull(Object obj)

还有另一个方法,可以用来强制一个值不为 null,否则会抛出 NullPointerException:

T Objects.requireNonNull(T obj);

注:Objects 类是在 Java 7 中添加的,但是 isNull() 和 nonNull() 方法仅在 Java 8 中添加。参考链接:https://stackoverflow.com/questions/25642585/how-to-check-if-object-is-null-or-not-except-null

英文:

The easiest way to check is entity == null. There is no shorter way to do that.

Note that there is a method for this in the standard lib:

Objects.isNull(Object obj)

And another one which is the opposite of the above one:

Objects.nonNull(Object obj)

And there is yet another one which can be used to force a value to be not null, it throws a NullPointerException otherwise:

T Objects.requireNonNull(T obj);

Note: The Objects class was added in Java 7, but the isNull() and nonNull() methods were added only in Java 8. Ref :https://stackoverflow.com/questions/25642585/how-to-check-if-object-is-null-or-not-except-null

huangapple
  • 本文由 发表于 2020年1月30日 18:54:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/59984355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定