javagroovygroovyshell

Avoiding reinitialsation of groovy shell for each record


I am trying to implement the following code:-

        for(int i = 0; i < records.length; i++){
            Binding binding=new Binding();
            binding.setVariable("val1",records[i][0]);
            binding.setVariable("val2",records[i][1]);
            binding.setVariable("val3",records[i][2]);
            GroovyShell shell=new GroovyShell(binding);
            Object value = shell.evaluate(code);
            System.out.println(value.toString());
        };

I don't want to create GroovyShell again and again for each record, but I am not able to see another option. From what I have seen, I can't provide a new binding to the same groovy shell, since binding can be provided only while creating the shell and not afterwards.

I have tried changing the binding object after creating groovy shell but it is giving me an error.

Do I have an alternative to reinitializing the groovy shell again and again for each record? I just want to pass the variables record[i][0],record[i][1],record[i][2] to the shell.


Solution

  • use GroovyShell.parse(code)

    Script script = new GroovyShell().parse(code);
    
    for(int i = 0; i < records.length; i++){
        Binding binding=new Binding();
        binding.setVariable("val1",records[i][0]);
        binding.setVariable("val2",records[i][1]);
        binding.setVariable("val3",records[i][2]);
        script.setBinding(binding);
        Object value = script.run();
        System.out.println(value.toString());
    };