Given the following groovy class:
class A {
static x = { }
}
How do I check if class A has defined a static property called 'x'? Neither option below seems to work:
A.hasProperty('x')
A.metaClass.hasProperty('x')
I couldn't see a groovier way of doing this other than using Java's reflection API:
import static java.lang.reflect.Modifier.isStatic
class A {
static x = 1
}
def result = A.class.declaredFields.find {
it.name == 'x' && isStatic(it.modifiers)
}
println result == null ? 'class does not contain static X' :
'class contains static X'
Look at GrailsClassUtils.getStaticFieldValue - it returns a static field value by name, null if no property exist or not set. You may look at implementation if that's helpful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With