How to verify if an object has certain property?

前端 未结 4 1979
轻奢々
轻奢々 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 01:58

    You can write your own method via meta-programming:

    class Foo {
        def name = "Mozart"
    }
    
    def f = new Foo()
    
    Object.metaClass.getPropertyOrElse = { prop, defaultVal ->
        delegate.hasProperty(prop) ? delegate."${prop}" : defaultVal
    }
    
    assert "Mozart" == f.getPropertyOrElse("name", "")
    assert "Salzburg" == f.getPropertyOrElse("city", "Salzburg")
    

提交回复
热议问题