views:

31

answers:

1

I'm trying to list the properties (i.e. all properties that have a getter method) using Groovy. I can do this using myObj.properties.each { k,v -> println v} and that works fine. But, that also prints for the entire superclass hierarchy as well. If I just want to list the properties for the current class (and not the super class), is that possible?

+2  A: 

Here's a way that I hacked out but maybe you can build on it.

class Abc {

    def a
    def b

}

class Xyz extends Abc {
    def c
    def d
}

def xyz = new Xyz(c:1,d:2)

xyz.metaClass.methods.findAll{it.declaringClass.name == xyz.class.name}.each { 
    if(it.name.startsWith("get"))  {
        println  xyz.metaClass.invokeMethod(xyz.class,xyz,it.name,null,false,true)
    }
}
stan229
@Stan, thanks. That's what I was thinking, but was hoping there was a "groovier" way to do it.
Jeff Storey