How to verify if an object has certain property?

前端 未结 4 1978
轻奢々
轻奢々 2020-12-29 01:46

I want to use either a value of expected property or a specified default. How to achieve this in groovy?

Let\'s look at the example:

def printName(ob         


        
4条回答
  •  时光说笑
    2020-12-29 02:02

    You can use hasProperty. Example:

    if (object.hasProperty('name') && object.name) {
        println object.name
    } else {
        println object
    }
    

    If you're using a variable for the property name, you can use this:

    String propName = 'name'
    if (object.hasProperty(propName) && object."$propName") {
        ...
    }
    

提交回复
热议问题