鉴于以下groovy类:
?class A {
static x = { }
}
Run Code Online (Sandbox Code Playgroud)
如何检查A类是否定义了名为"x"的静态属性?以下两个选项似乎都不起作用:
A.hasProperty('x')
A.metaClass.hasProperty('x')
Run Code Online (Sandbox Code Playgroud)
除了使用Java的反射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'
Run Code Online (Sandbox Code Playgroud)
我看不到任何明显的方法来直接检查静态属性,但是检查名为的静态方法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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4832 次 |
| 最近记录: |