在Java中检查对象的NULL的最佳方法 [英] Best way to check NULL for objects in Java
问题描述
我有一个检查NULL 从对象中提取的值的解决方案,但是我觉得可能有比我在这里做的更好的方法。所以请用代码片段向我建议最佳方式:)
I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. So please suggest me the best ways with code snippet :)
我将把我的xml内容传递给解组方法&然后将unmarshalledValues传递给null检查方法(即ValidateInputFiled)
I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (i.e ValidateInputFiled )
Contents unmarshalledValues = unmarshalingContent( xml );
inputCheck = ValidateInputField( unmarshalledValues );
我的XML元素有一个POJO,如下所述,
I have a POJO for my XML elements as mentioned below,
@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;
}
}
我已经定义了ValidateInputFiled,如下所述
I have defined ValidateInputFiled as mentioned below
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;
}
这里我希望避免对每个字符串值进行NULL检查(即A,B,C,D)我可以使用集合或列表对内容或unmarshalledValues进行空检查吗?
Here i am looking to avoid NULL check for each String Values ( i.e A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ?
推荐答案
<那是你在找什么?
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;
}
这篇关于在Java中检查对象的NULL的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!