Groovy: how to test if a property access will be successful?

ぃ、小莉子 提交于 2020-04-07 17:01:32

问题


I have a variable Object foo, which is not null. I want to use foo.bar, but only if it won't bomb me with 'No such property: bar for class: Whatever'.

How should I do the following test:

if (/*test-here*/) {
  use(foo.bar)
}

回答1:


Use object.hasProperty(propertyName). This will return a truthy value (the property reference) if the property exists. Also object.metaClass.hasProperty(instance, propertyName) is possible. Use object.respondsTo(methodName) to test for method existence.




回答2:


I do this in my Gradle scripts:

if(project.hasProperty("propertyThatMightExist")){
    use(propertyThatMightExist)
}



回答3:


If you're doing it on lots of foos and bars you could write (once, but before foo is created):

Object.metaClass.getPropertySafe = 
    { delegate.hasProperty(it)?.getProperty(delegate) }

Then you can write:

foo.getPropertySafe('bar')



回答4:


This worked for me :

Customer.metaClass.properties.find{it.name == 'propertyName'}.

Customer in this example is a domain class. Not sure if it will work for a plain Groovy class




回答5:


boolean exist = Person.metaClass.properties.any{it.name == 'propName'}

if propName is an attribute ,exist=true // vice versa




回答6:


I can't speak for Groovy specifically, but in just about every dynamic language I've ever used the idiomatic way of doing this is to just do it, and catch the exception if it gets thrown, and in the exception handler do whatever you need to do to handle the situation sensibly.



来源:https://stackoverflow.com/questions/5240680/groovy-how-to-test-if-a-property-access-will-be-successful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!