Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

groovy

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
like image 589
Kshitiz Sharma Avatar asked Jul 30 '13 12:07

Kshitiz Sharma


People also ask

What types of variables does Groovy support?

Groovy supports all Java types (primitive and reference types). All primitives types are auto converted to their wrapper types. So int a = 2 will become Integer a = 2. When no type is used, variables act like they are of type Object, so they can be reassigned to different types:

How do you determine the type of an object in Groovy?

Groovy: Determine type of an object Creating an object called obj of type java.util.ArrayList which implements the java.util.List interface. instanceof checks if obj is the subclass of some class. getClass returns the exact type of an object.

What are classes and objects in Groovy?

In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data.

What is the difference between Java and groovy?

In Groovy, all variables are initialized (even local) with their default values (just like instance variable). In Java, if we try to use a local variable without initializing: Regarding types, we have all three above options to use for method parameters, but return type must be the actual type or def:


1 Answers

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}" }
like image 149
tim_yates Avatar answered Oct 19 '22 21:10

tim_yates