1
votes

I'm using Groovy Interpreter in Java class, I'm trying to define a method and call it, here is my code:

        Binding binding = new Binding();
        binding.setVariable("aa", 1);
        binding.setVariable("bb", 2);

        GroovyShell shell = new GroovyShell(binding);
        shell.evaluate("int add(int a,int b){return (a+b)}");

        int   value =(int) shell.evaluate("add(aa,bb);");
        System.out.println(value);

And I've got this error:

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Script2.add() is applicable for argument types: (java.lang.Integer, java.lang.Integer) values: [1, 2] Possible solutions: any(), wait(), run(), run(), find(), wait(long, int)

Please tell me how to define a function inside groovy and why my code is not working.

Best regards,

1
What happens if you paste all of the Groovy code into a single string and evaluate once? Based on the class name Script2, I think the shell treats each evaluate call independently. - chrylis -cautiouslyoptimistic-
@chrylis You're right, this works when I evaluate all the script in one shell evaluation, thank you - Mehdi Bouzidi

1 Answers

3
votes

When you use GroovyShell#evaluate, the shell compiles the entire script into a JVM class, loads it, and runs it, then returns the result. This process is independent for each evaluate call (note that the name of the class is Script2; the method was defined in Script1), and so your method isn't available in the second call.

Options for working around this include simple string concatenation before evaluating (this will work for your own scripts but could have problems if something in the scripts calls return) or using the more complex GroovyScriptEngine.