为什么在我需要它时,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);
Run Code Online (Sandbox Code Playgroud)
我知道JsonSlurper使用元编程,为什么我会得到以下内容:
Caught: java.lang.NullPointerException: Cannot get property 'properties' on null object
at MetaTest.printMeta(MetaTest.groovy:17)
at MetaTest.run(MetaTest.groovy:24)
我完全没有想法.
谢谢!
Joh*_*ham 15
我从来没有玩过JSON的东西,但通常当你试图在地图上调用.metaClass时会发生这种情况.
如果我不知道我之前正在调用的类,我通常会专门调用.getMetaClass().否则,当我试图将地图作为模拟对象传递时,这种事情会让我感到困惑.
(这与您通常希望调用.getClass()而不是.class来获取Class对象的原因相同.)
| 归档时间: |
|
| 查看次数: |
1869 次 |
| 最近记录: |