检查对象为空

时间:2013-01-22 16:27:18

标签: java

基本上如何检查对象是空还是空。我的意思是,如果我实例化了一个对象,但它的所有值或字段都为空,那么如果它是空的,我如何检查代码呢?

我试过了;

if (doc != null){
.... do something

但它似乎不起作用。

8 个答案:

答案 0 :(得分:25)

你不能直接做,你应该提供自己的方式来检查这一点。例如

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

或者将所有字段设置为final并在构造函数中初始化它们,以便确保所有字段都已初始化。

答案 1 :(得分:3)

您应该针对null进行检查。

如果要检查对象x是否为空,可以执行以下操作:

    if(x != null)

但是如果它不为null,则它可以具有null或空的属性。您将明确检查这些:

    if(x.getProperty() != null)

"空"检查,这取决于涉及的类型。对于Java String,您通常会这样做:

    if(str != null && !str.isEmpty())

由于您没有提及任何具体问题,很难说清楚。

答案 2 :(得分:3)

这可以通过java反射来完成,如果该对象存在任何一个属性值,则此方法返回false,希望对您有所帮助

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}

答案 3 :(得分:1)

我建议你添加单独的重载方法,并将它们添加到你的项目Utility / Utilities类。

  

检查Collection是否为空或为空

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

或使用Apache Commons CollectionUtils.isEmpty()

  

检查Map是否为空或为空

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

或使用Apache Commons MapUtils.isEmpty()

  

检查String empty或null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

或使用Apache Commons StringUtils.isBlank()

要检查对象是否为空是很容易的,但要验证它是否为空是棘手的,因为对象可以有许多私有或继承的变量和嵌套对象,这些对象都应为空。因为所有需要被验证或者一些isEmpty()方法在所有对象中都会验证对象的空虚。

答案 4 :(得分:1)

在Java中,您可以使用Object utils进行验证。

import static java.util.Objects.isNull;
if(IsNull(yourObject)){
  //your block here
}

答案 5 :(得分:0)

如果您的对象包含对象,则检查它们是否为空,如果它具有基元检查它们的默认值。

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

答案 6 :(得分:0)

假设

data = {};

if( if(!$.isEmptyObject(data)))
{
     document.write("Object is empty);
}

else{
    document.write("Object is not empty);
}

它为我工作,并且它是检查对象是否为空的简单方法

答案 7 :(得分:0)

我有办法,你们告诉我它有多好。

创建该类的新对象,并将其与您的对象(您要检查其是否为空)进行比较。

要正确执行此操作:

覆盖模型类以及对象所属类的类的对象的hashCode()和equals()方法,例如:

人员课程(主要模型课程):

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

地址类(在Person类中使用):

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

现在在主要班级:

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

我希望这是最好的方法,而不是在每个成员变量上都设置条件。

让我知道!

相关问题