How to check if groovy class has a static property?

Given the following groovy class:

class A {
    static x = { }
}

How to check if class A has set the static property "x"? None of the options below work:

A.hasProperty('x')
A.metaClass.hasProperty('x')
+5
source share
5 answers

I could not see a more attractive way to do this other than using the Java 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'
+5
source

Take a look at GrailsClassUtils.getStaticFieldValue - it returns the value of a static field by name, null if the property does not exist or is not set. You can take a look at the implementation if this is useful

+3
source
A.metaClass.hasProperty(A,'x')

A.metaClass.respondsTo(A,'getX')
+1

, getProperty ( )

def getStaticProperty(String name, Class clazz) {
  def noArgs = [].toArray()
  def methodName = 'get' + name[0].toUpperCase()

  if (name.size() > 1) {
    methodName += name[1..-1]
  }

  clazz.metaClass.getStaticMetaMethod(methodName, noArgs)
}

// class that will be used in tests
class Foo {

  static String x = 'bar'
  static Integer num = 3
}

// tests
assert getStaticProperty('x', Foo)
assert getStaticProperty('num', Foo)
assert getStaticProperty('noSuchProperty', Foo) == null
0

2017 groovy 2.4.x, :

A.metaClass.getMetaProperty('x') != null

, , , ( ), (, java). MetaProperty , . , , . , , .

, , .

sudhir, , , getDeclaredFields , , , getter setter. , grails. , .

SteveD . , "" . , :

def hasProperty = { Class c, String propertyName ->
    if (!propertyName)
        return false;
    String p2 = propertyName.substring(0, 1).toUpperCase()
    if (propertyName.length()> 1)
        p2 += propertyName.substring(1)
    return c.declaredFields.find {
        it.name == propertyName /* && isStatic(it.modifiers) */
    } || c.declaredMethods.find {
        it.name == ('get' + p2) /* && isStatic(it.modifiers) */
    } || c.declaredMethods.find {
        it.name == ('is' + p2) /* && isStatic(it.modifiers) */
    } || c.declaredMethods.find {
        it.name == ('set' + p2)/* && isStatic(it.modifiers) */
    }
}

, , ( java.lang.reflect.Modifier.isStatic uncomment isStatic ). , .

0

All Articles