0

I'm not really sure how I can explain this, but here goes:

I want to be able to "insert" some commands into parts of my code which will be loaded from external files. To parse and execute these commands, I presumably have to use some scripting like BeanShell's eval method. The problem is that it doesn't seem to recognize the instance/method it's inside of. As a very basic example, I want to do something like

    public void somethingHappens()
    {
        Foo foo = new Foo();
        Interpreter i = new Interpreter();
        i.eval("print(foo.getName());");
    }

Is this possible? Should I use other scripting tools?

pg-robban
  • 1,395
  • 4
  • 21
  • 42

2 Answers2

1

If you're using 1.6, you can use the built in JavaScript support.

The Java Scripting Programmer's Guide explains how to import Java classes into your script.

Code example 9 in this article explains how to pass objects into the script's scope.

Devon_C_Miller
  • 16,248
  • 3
  • 45
  • 71
  • Thanks, I didn't know about the put method in the ScriptEngine class. I believe this will solve my issues so far. – pg-robban Sep 10 '09 at 21:44
0

Using beanshell, this is something you can try

package beanshell;

import bsh.EvalError;
import bsh.Interpreter;

public class DemoExample {

    public static void main( String [] args ) throws EvalError  {
        Interpreter i = new bsh.Interpreter();
        String usrIp = "if(\"abc\".equals(\"abc\")){"
                + "demoExmp.printValue(\"Rohit\");"
                + "}";

        i.eval(""
                + "import beanshell.DemoExample;"
                + "DemoExample demoExmp = new beanshell.DemoExample();"
                + ""+usrIp);
    }

    public static void printValue(String strVal){
        System.out.println("Printing Value "+strVal);
    }
}
Rohit Borse
  • 75
  • 1
  • 10