简体   繁体   English

在Java中检查对象的NULL的最佳方法

[英]Best way to check NULL for objects in Java

I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. 我有一个解决方案来检查从对象中提取的NULL值,但我觉得可能有比我在这里做的更好的方法。 So please suggest me the best ways with code snippet :) 所以请建议我使用代码片段的最佳方法 :)

I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (ie ValidateInputFiled ) 我将把我的xml内容传递给unmarshalling方法然后将unmarshalledValues传递给null检查方法(即ValidateInputFiled)

Contents unmarshalledValues = unmarshalingContent( xml ); 
inputCheck = ValidateInputField( unmarshalledValues );

I have a POJO for my XML elements as mentioned below, 我有一个POJO用于​​我的XML元素,如下所述,

 @XmlRootElement( name = "contents" )
    public class Contents
    {
        @XmlElement
        String A;

        @XmlElement
        String B;

        @XmlElement
        String C;

        @XmlAttribute
        String D;

       public String getA()
      {
        return A;
      }

       public String getB()
      {
        return B;
      }

       public String getC()
      {
        return C;
      }

       public String getD()
      {
        return D;
      }
}

I have defined ValidateInputFiled as mentioned below 我已经定义了ValidateInputFiled,如下所述

public Boolean ValidateInputField( Contents unmarshalledValues )
    {
        int checker = 0;
        Boolean listCheck = false;

        // Extracting unmarshalled values from xml
        String A= unmarshalledValues.getA();
        String B= unmarshalledValues.getB();
        String C = unmarshalledValues.getC();
        String D= unmarshalledValues.getD();

        if ( A== null || A.isEmpty() )
        {
            checker++;
        }

        if ( B== null || B.isEmpty() )
        {
            checker++;
        }

        if ( C== null || C.isEmpty() )
        {
            checker++;
        }

        if ( D== null || D.isEmpty() )
        {
            checker++;
        }

        if ( checker == 0 )
        {
            listCheck = true;
        }

        return listCheck;

    }

Here i am looking to avoid NULL check for each String Values ( ie A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ? 在这里,我希望避免每个字符串值(即A,B,C,D)的NULL检查,而不是我可以使用集合或列表对内容或unmarshalledValues进行空检查?

public static boolean isNullOrEmpty(String a) {
    return a == null || a.isEmpty();
}

Call that for each value. 为每个值调用它。 You may want to think about adding them all to a list and then iterating through them, incrementing checker if they're !isNullOrEmpty to save code bloat if you have lots for fields. 您可能想要考虑将它们全部添加到列表中,然后迭代它们,如果它们是,则递增检查器!isNullOrEmpty以保存代码膨胀,如果您有很多字段。

PS: Make your fields private to preserve encapsulation. PS:将您的字段设为私有以保留封装。

pps: don't bother with a seperate boolean just return checker == 0; pps:不要打扰单独的布尔值只return checker == 0; to keep the code neat. 保持代码整洁。

Is that what you are looking for ? 那是你在找什么?

public Boolean ValidateInputField(Contents unmarshalledValues) {
    // Extracting unmarshalled values from xml
    String A = unmarshalledValues.getA();
    String B = unmarshalledValues.getB();
    String C = unmarshalledValues.getC();
    String D = unmarshalledValues.getD();
    return checkNull(A, B, C, D);
}

private static boolean checkNull(String... strings) {
    for (String string : strings) {
        if (string == null || string.isEmpty()) {
            return false;
        }
    }
    return true;
}

I use the apache commons StringUtils library for this type of thing. 我使用apache commons StringUtils库来处理这类事情。 It has a check that includes null or empty spaces, plus other combinations depending on how you treat empty spaces. 它有一个包含空格或空格的检查,以及其他组合,具体取决于您处理空格的方式。 Pretty much code like Jeff here gave you, but i like having other methods they include. 像Jeff这样的代码几乎给了你,但我喜欢它们包含的其他方法。

You can also avoid nulls alltogether by coding your getters to return "" if a value == null. 如果值== null,您还可以通过编写getter来返回“”来完全避免null。 Then you would not have to check each field for null. 然后,您不必检查每个字段是否为null。

commons-lang有一个你可以使用的Validate类:

Validate.notNull( unmarshalledValues.getA() );

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness: Java 8的非反射解决方案,不使用一系列if,将流式传输所有字段并检查null:

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. 对于null属性,这将返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM