Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Groovy's "metaClass" returns null

Tags:

groovy

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!

like image 810
djcredo Avatar asked Dec 20 '09 01:12

djcredo


1 Answers

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

like image 180
John Stoneham Avatar answered Oct 20 '22 10:10

John Stoneham