Tuesday, January 4, 2011

Groovy MetaClassing Issue?

Does someone want to explain this to me?

Or can?

Here is my basic problem. I have a class, it takes a method, i want to intercept it and depending on the object do something with it.

It can accept some kind of Collection usually.

Now here is the problem. You can use the object fine. But when you do something like "list as Set" ... when it hits the invokeMethod the arg is a PojoWrapper and NOT a Set object. Note if you called the method directly it is a Set.

This provides all sorts of problems, for one you cant do args[0].getClass() or it will thrown an NPE.

I tried to do just about anything to determine the variable when it is a PojoWrapper but everything threw an NPE.

Using groovy 1.7.5 ... cut and paste this into your groovy console and you will see


def a = [1,2,3]

def b = a as Set

t = new Temp()
t.stuff(a as Set)
println "*******"

t.metaClass.invokeMethod {String name, args ->
def ourVar = args[0]
println "name : $name / args : " + args[0]
if (ourVar instanceof Set) {
println "its a set"
}
else if (ourVar instanceof Collection) {
println "its a collection"
}
else if (ourVar instanceof org.codehaus.groovy.runtime.wrappers.PojoWrapper) {
println "Wrapper"
println ourVar
def list = []
list.addAll(ourVar)
println list.getClass()
}
//println ourVar.class
println "----"
}

t.joe(a)
t.joe(b)
t.joe(a as Set)

class Temp {

def stuff(t) {
println t
println t.getClass()
}

def invokeMethod(String name, args) {
println "huhg:: " + args
}
}


Tweak it, to me its pretty odd, i am using something similair in my code, and i can come up with a few hacks but none that are good. I'd really like to be able to determine what that PojoWrapper is.

Note if u do the as Set and set to a variable before hand it works fine.