如何检查Pojo的属性何时为空,然后Pojo必须使用Groovy为null

时间:2016-08-18 07:02:43

标签: groovy

如何查看Person,然后自动检查年龄为空?

def person = new Person(name:'Jack')
//when i check person, how can i direct check the person.age is null and return false
if(person){

}else{
    log.info "person is not exist"
} 

class Person{
    def name
    def age
}

3 个答案:

答案 0 :(得分:1)

我认为,你应该在你的案例中使用Groovy truth的东西:

class Person{
  def name
  int age
  boolean asBoolean(){
    0 < age
  }
}

assert new Person( age:2 )
assert !new Person( age:0 )

答案 1 :(得分:0)

你可以safe navigation operator

if (person?.age) { //if either person or age is null 
                   //(or other falsy value like 0) it will be falsy
      //...
}

您也可以进行连锁检查:

if(person && person.age){}

顺便说一句:类的实例应该以小写开头,所以你应该写:

def person = new Person(name:'Jack')

答案 2 :(得分:0)

似乎工作......
有人可以给我建议吗?

import groovy.util.logging.Log4j
import java.lang.reflect.Field
import org.junit.Test

@Log4j
class TestNull {

    @Test
    void testNotNull(){
        ObjectA a = new ObjectA(a : "AAA", b : "BBB", c : "CCC", d:"DDD")
        if(isNull(a)){
            log.info "a is not null"
        }else{
            log.info "a is null object"
        }
    }

    @Test
    void testIsNull(){
        ObjectA a = new ObjectA(a : "AAA", b : "BBB", c : "CCC")
        if(isNull(a)){
            log.info "a is not null"
        }else{
            log.info "a is null object"
        }
    }

    def isNull(Object obj){
        Boolean value = true
        obj.getClass().getDeclaredFields().each{ Field field ->
            field.setAccessible(true)

            // check field is customize or not 
            if(!field.isSynthetic()){
                if(!field.get(obj)){
                    log.info "${field}_${field.get(obj)}"
                    value = false
                    return value
                }
            }
        }
        return value
    }
}

class ObjectA {
    def a
    def b
    def c
    def d
}