Can I instantiate beanshell class sourced from ano

2019-04-11 19:24发布

I would like to run class imported from different beanshell file. But I've no idea how instantiate class from main beanshell file. Is this possible?

Class which I import:

class HelloW {
public void run(){
    print("Hello World");
}
}

Main beanshell file which should run and instantiate class:

Interpreter i = new Interpreter();
i.source("HelloW.bsh");

1条回答
2楼-- · 2019-04-11 20:21

The BeanShell documentation is pretty good in this area, so you should read through that first. In your case there are few issues. That said, there are Scripted Objects. Also, the .bsh file you start with needs to execute the scripted object. Taking your example this code should work:

Hello() {
 run(){
     print("Hello World");
 }

 return this;
}

myHello = Hello();
myHello.run(); // Hello World

*UPDATED answer for version BeanShell 2.0b1 and later which support scripted classes *:

I created two beanshell files and placed them in a directory "scripts".

The first "executor.bsh" is what you are calling the "parent" script, I believe.

// executor.bsh

addClassPath(".");
importCommands("scripts");

source(); // This runs the script which defines the class(es)

x = new HelloWorld();
x.start();

The second file contains the scripted class. Note that I am using a Scripted Command and according to BeanShell documentation, the file name must be the same as the command name.

// source.bsh

source() {
    public class HelloWorld extends Thread {
        count = 5;
        public void run() {
            for(i=0; i<count; i++)
                print("Hello World!");
        }

    }
}

I invoked executor.bsh in a java class with:

Interpreter i = new Interpreter();
i.source("scripts/executor.bsh");

// Object val = null;
    // val = i.source("scripts/executor.bsh");
// System.out.println("Class:" + val.getClass().getCanonicalName());
// Method m = val.getClass().getMethod("start", null);
// m.invoke(val, null);

Note that I left some commented code which also shows me executing the scripted class from Java, using Reflection. And this is the result:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
查看更多
登录 后发表回答