Dónal
Dónal

Reputation: 187499

get Groovy class' closure property names

Given the following Groovy class:

class MyClass {

  def someClosure = {}
  def someClosure2 = {}

  private privateClosure = {

  }

  def someVal = 'sfsdf'

  String someMethod() {}
}

I need a way to retrieve the names of all public properties that have closure assigned to them, so the correct result for this class would be ['someClosure', 'someClosure2'].

I can assume that all the classes of interest have a default constructor, so if it makes things easier, I could retrieve the properties from an instance via

def instance = MyClass.newInstance()

Upvotes: 2

Views: 1032

Answers (1)

ataylor
ataylor

Reputation: 66059

You can simply check the value of every groovy property:

class Test {
    def aClosure = {}
    def notClosure = "blat"
    private privateClosure = {}
}

t = new Test()
closurePropNames = t.properties.findResults { name, value ->
    value instanceof Closure ? name : null
}
assert closurePropNames == ['aClosure']

The private fields are not considered groovy properties, so they won't be included in the results.

Upvotes: 6

Related Questions