How to avoid MissingPropertyException

前端 未结 2 1491
无人及你
无人及你 2021-01-04 09:29

If an object does not have a property and I am accessing the property, we get a MissingPropertyException. Can I do something similar to safe null (?.

相关标签:
2条回答
  • 2021-01-04 10:13

    One option would be:

    def result = obj.hasProperty( 'b' ) ? obj.b : null
    

    Which would return null if the object doesn't have the property...

    Another would be to add propertyMissing to your class like so:

    def propertyMissing( name ) {
      null
    }
    

    This means that any missing properties would just result in null.

    0 讨论(0)
  • 2021-01-04 10:31

    You can also use try/catch

    try
    {   env.GERRIT_TOPIC=GERRIT_TOPIC
    }
    catch (e_val)
    {   echo 'missing GERRIT_TOPIC'
    }
    
    0 讨论(0)
提交回复
热议问题