pg-robban
pg-robban

Reputation: 1435

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?

Upvotes: 0

Views: 1446

Answers (2)

Rohit Borse
Rohit Borse

Reputation: 85

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);
    }
}

Upvotes: 0

Devon_C_Miller
Devon_C_Miller

Reputation: 16528

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.

Upvotes: 1

Related Questions