How to verify if an object has certain property?

前端 未结 4 1977
轻奢々
轻奢々 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")
    
    0 讨论(0)
  • 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") {
        ...
    }
    
    0 讨论(0)
  • 2020-12-29 02:06

    Assuming your object is a Groovy class, you can use hasProperty in the object metaClass like so:

    def printName( o ) {
      if( o.metaClass.hasProperty( o, 'name' ) && o.name ) {
        println "Printing Name : $o.name"
      }
      else {
        println o
      }
    }
    

    So, then given two classes:

    class Named {
      String name
      int age
    
      String toString() { "toString Named:$name/$age" }
    }
    
    class Unnamed {
      int age
    
      String toString() { "toString Unnamed:$age" }
    }
    

    You can create instance of them, and test:

    def a = new Named( name: 'tim', age: 21 )
    def b = new Unnamed( age: 32 )
    
    printName( a )
    printName( b )
    

    Which should output:

    Printing Name : tim
    toString Unnamed:32
    
    0 讨论(0)
  • 2020-12-29 02:13

    If I simply want to assert that an object has some property, I just test the following:

    assertNotNull(myObject.hasProperty('myProperty').name)
    

    If myObject does not have myProperty the assertion will fail with a null pointer exception:

    java.lang.NullPointerException: Cannot get property 'name' on null object
    
    0 讨论(0)
提交回复
热议问题