Kshitiz Sharma
Kshitiz Sharma

Reputation: 18627

How to get all the variables of a groovy object or class?

To see list of methods in a class I can do this -

String.methods.each {println it}

How do I list all the variables of an instance or all the static variables of a class?

Edit1:

enter image description here

enter image description here

Edit2:

HoneyBadger.java

public class HoneyBadger {
    public int badassFactor;
    protected int emoFactor;
    private int sleepTime;
}

test.groovy -

HoneyBadger.metaClass.properties.each {println it.name }

Output -

class

Upvotes: 6

Views: 15715

Answers (1)

tim_yates
tim_yates

Reputation: 171154

You could do:

String.metaClass.properties.each { println it.name }

An alternative (given your new example) would be:

import java.lang.reflect.Modifier

HoneyBadger.declaredFields
           .findAll { !it.synthetic }
           .each { println "${Modifier.toString( it.modifiers )} ${it.name} : ${it.type}" }

Upvotes: 12

Related Questions