Rob H
Rob H

Reputation: 15000

Reflect on functions declared in a Groovy script

Is there a way to obtain reflection data on functions declared in a Groovy script that has been evaluated via a GroovyShell object? Specifically, I want to enumerate the functions in a script and access annotations attached to them.

Upvotes: 3

Views: 1007

Answers (2)

Rob H
Rob H

Reputation: 15000

After some experimenting, I found this to be the easiest way:

GroovyShell shell = new GroovyShell();
Script script = (Script)shell.parse(new FileReader("x.groovy"));
Method[] methods = script.getClass().getMethods();

The method array has all of the functions defined in the script and I can get the annotations from them.

Upvotes: 1

Anton Arhipov
Anton Arhipov

Reputation: 6591

Put this to the last line of Groovy script - it will serve as a return value from the script, a-la:

 // x.groovy
 def foo(){}
 def bar(){}
 this

Then, from Java code you can do the following:

 GroovyShell shell = new GroovyShell();
 Script script = (Script) shell.evaluate(new File("x.groovy"));

Now it seems that there's no option to introspect the annotations of Groovy script from Java directly. However, you can implement a method within the same Groovy script and call that one from Java code, for instance:

//groovy
def test(String m){
  method = x.getMethod(m, [] as Class[])
  assert method.isAnnotationPresent(X)
}

//java
script.getMetaClass().invokeMethod(script, "test", "foo");

Upvotes: 2

Related Questions