Get parsed groovy script methods

Beto Neto

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.

Szymon Stepniak

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Global methods in Groovy script

How to get the script name in Groovy

(de)serialization of parsed Groovy scripts

Get all pipeline Jobs in Jenkins Groovy Script

How to get Jenkins build parameters in the Groovy script?

groovy script regular expression to get digit

How to get all method names of a class without inherited methods with Groovy?

How do I concatenate a dynamic string value using Groovy to JSON response after it's parsed to get a specific node value in JSON

get git repository from multi pipelines jobs with groovy script

Jenkins groovy script parameter get from another job

How to get environment variable in Jenkins Groovy script console?

Why does this Groovy script fail in Jenkins to get the job parameters?

Get build requestor using Groovy script (Jenkins / email-ext)

How to get a list of running jenkins builds via groovy script?

How to get file.creationtime attribute in nifi groovy script

Get text value from xml in soapui groovy script

Testing private methods in groovy

Body is not getting parsed in GET method

Use a groovy script from another groovy script

Grails[Groovy],How to get list of all methods a class has with out those inherited?

Script parsed using DOMParser does not execute

JSF components not parsed inside a <script> block

groovy script - sh with variable

Execute a .jar in a Groovy script

groovy, script:this and jenkinsfile

Understanding a small groovy script

Variable visibility in a Groovy Script

groovy script in jenkins fails

Variable zero in groovy script