Search code examples
javascriptingbeanshell

Executing script inside method with BeanShell


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?


Solution

  • 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.