Search code examples
groovygroovyshell

Get parsed groovy script methods


I have this groovy script:

GroovyShell shell = new GroovyShell();
Script script = shell.parse("def myStuff(a){ return a }");

How can I get from script the list of all declared functions?

I already tried script.getMetaClass().getMetaMethods() but myStuff function isn't listed.


Solution

  • There are two ways to invoke your method:

    1. You can search for it in script.getMetaClass().getMethods()

    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell();
        Script script = shell.parse("def myStuff(a){ return a }");
    
        script.getMetaClass()
                .getMethods()
                .stream()
                .filter(it -> it.getName().equals("myStuff"))
                .findAny()
                .ifPresent(method -> {
                    final Object result = method.doMethodInvoke(script, new Object[]{3});
                    System.out.println("result = " + result);
                });
    }
    

    Output:

    result = 3
    

    2. You can use script.invokeMethod(String name, Object args)

    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell();
        Script script = shell.parse("def myStuff(a){ return a }");
    
        System.out.println(script.invokeMethod("myStuff", 5));
    }
    

    Output:

    5