Groovy List of all properties for the class.

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

+5
source share
2 answers

Here is the way I hacked, but maybe you can build 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)
    }
}
+3
source

Try the following:

myObj.declaredFields.collect{it.name}
+1
source

All Articles