Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy List all properties for class

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?

like image 245
Jeff Storey Avatar asked Oct 26 '10 20:10

Jeff Storey


People also ask

What are Groovy properties?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.

How do you make a POJO on Groovy?

To do this, go to the context menu of a table (or several tables) and press Scripted Extension → Generate POJO. groovy. Choose a destination folder, and that's it!

What is Groovy abstract class?

Abstract ClassesTheir members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. Abstract classes must be declared with abstract keyword. Abstract methods must also be declared with abstract keyword.

How do you call a class in Groovy?

In Groovy we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.


2 Answers

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)
    }
}
like image 131
stan229 Avatar answered Sep 28 '22 01:09

stan229


Try with the following:

myObj.declaredFields.collect{it.name}
like image 33
Damien GOUYETTE Avatar answered Sep 28 '22 03:09

Damien GOUYETTE