Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a groovy class has a static property?

Tags:

groovy

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')
like image 946
tuler Avatar asked Jan 04 '12 10:01

tuler


2 Answers

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'
like image 195
SteveD Avatar answered Sep 30 '22 13:09

SteveD


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

like image 35
Sudhir N Avatar answered Sep 30 '22 14:09

Sudhir N