When you run a GroovyShell execute it is like you are creating a class with 
that code in it. The “printme” variable is a local variable to the method, so 
it cannot be seen outside of that method. Using Groovy doesn’t allow you do 
violate the scope of Java – a class can’t know the local variables of the 
method that created/called it.

You have to do what you say, that is put into the shell’s binding all of the 
variables that you might possibly use, which is the common strategy for this 
problem. A class to hold all of the data can be used if you want to limit the 
number of bindings (i.e. some kind of state class). The closest that you can 
get to what you are doing is to transform all of the local variables you want 
to access into instance fields and then set “this” into the binding.

Jason

From: Ravi Kapoor [mailto:ravikapoor...@gmail.com]
Sent: Wednesday, July 08, 2015 3:11 PM
To: users@groovy.incubator.apache.org
Subject: how to dynamically evaluate expression in java code running inside 
groovy


I am trying to run my whole java project in Groovy.
I have run into an issue i.e. anytime I want to do anything dynamically, I have 
to bind all possible things that may exist inside the expression.
This is very inefficient.

Instead I want to be able to pass my existing context to groovy shell. How do I 
do this?

I am attaching a sample program highlighting the issue. This seems such an easy 
and obvious feature, but I am so stuck here. Thanks for helping.

Ravi


--------------------------------------------------------------------------------
package com.test;

import java.util.HashMap;
import java.util.Map;

import groovy.lang.*;

public class Test {

            public static void main(String[] args) {
                        GroovyClassLoader classLoader = new GroovyClassLoader();
            Binding binding = new Binding();
            Map<Object, Object> attributes = new HashMap<Object, Object>();

            GroovyShell shell = new GroovyShell(classLoader, binding);
            binding.setVariable("shell", shell);
                        shell.evaluate("new 
com.test.Test().runInsideGroovy(shell)");

            }

            public void runInsideGroovy(GroovyShell shell) {
                        System.out.println("inside groovy");

                        String printme = "secret";
                        shell.evaluate("System.err.println(printme)");
            }
}







----------------------------------------------------------------------
This email message and any attachments are for the sole use of the intended 
recipient(s). Any unauthorized review, use, disclosure or distribution is 
prohibited. If you are not the intended recipient, please contact the sender by 
reply email and destroy all copies of the original message and any attachments.

Reply via email to