tags:

views:

45

answers:

1

Hi,

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!

+5  A: 

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

John Stoneham
This happened to me though the metaClass wasn't invoked on a Map. Your answered help solving the problem though. Thx
ken