Can I instantiate beanshell class sourced from another Beanshell script?

穿精又带淫゛_ 提交于 2020-01-01 15:33:14

问题


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:


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!


来源:https://stackoverflow.com/questions/14213600/can-i-instantiate-beanshell-class-sourced-from-another-beanshell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!