为什么仅在需要时Groovy的“metaClass”属性返回null。例子:

import net.sf.json.groovy.JsonSlurper


@Grab(group='net.sf.json-lib', module='json-lib', version='2.3', classifier='jdk15')

def printMeta(obj) {

   obj.metaClass.properties.each {println "Property: ${it.name}"}
}

def raw = /{"test":"this is a test"}/

def json = new JsonSlurper().parseText(raw);
printMeta (json);

我知道JsonSlurper使用元编程,所以为什么会得到以下信息:
Caught: java.lang.NullPointerException: Cannot get property 'properties' on null object at MetaTest.printMeta(MetaTest.groovy:17) at MetaTest.run(MetaTest.groovy:24)
我全都没主意了。

谢谢!

最佳答案

我从没玩过JSON,但是通常在您尝试在 map 上调用.metaClass时会发生这种情况。

如果我不知道事先要调用的类,通常会专门调用.getMetaClass()。否则,当我尝试将 map 作为模拟对象传递时,这种事情会刺痛我。

(这与您通常要调用.getClass()而不是.class以获得Class对象的原因相同。)

关于groovy - 当Groovy的 "metaClass"返回null时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1934651/

10-11 22:14
查看更多