Search code examples
groovy

When Groovy's "metaClass" returns null


Why is it that just when I need it, Groovy's "metaClass" property returns null. Example:

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);

I know that JsonSlurper uses metaprogramming, so why do I get the following:

Caught: java.lang.NullPointerException: Cannot get property 'properties' on null object at MetaTest.printMeta(MetaTest.groovy:17) at MetaTest.run(MetaTest.groovy:24)

I'm all out of ideas.

Thanks!


Solution

  • I've never played with the JSON stuff at all, but usually this happens when you're trying to call .metaClass on a Map.

    If I don't know the class I'm calling on beforehand, I'll usually call .getMetaClass() specifically. Otherwise this sort of thing bites me when I'm trying to pass maps around as mock objects.

    (This is the same reason you usually want to call .getClass() instead of .class to get a Class object.)