我可以实例化来自另一个Beanshell脚本的beanshell类吗?

Pot*_*Tea 3 scripting beanshell

我想运行从不同的beanshell文件导入的类.但是我不知道如何从main beanshell文件中实例化类.这可能吗?

我导入的类:

class HelloW {
public void run(){
    print("Hello World");
}
}
Run Code Online (Sandbox Code Playgroud)

应该运行并实例化类的主beanhell文件:

Interpreter i = new Interpreter();
i.source("HelloW.bsh");
Run Code Online (Sandbox Code Playgroud)

Gar*_*McM 5

BeanShell的文档在这方面还不错,所以你应该通过先读.在你的情况下,几乎没有问题.也就是说,有脚本对象.此外,您开始使用的.bsh文件需要执行脚本对象.举个例子,这个代码应该有效:

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

 return this;
}

myHello = Hello();
myHello.run(); // Hello World
Run Code Online (Sandbox Code Playgroud)

*版本BeanShell 2.0b1及更高版本的更新答案,支持脚本类*:

我创建了两个beanshell文件并将它们放在"脚本"目录中.

我相信第一个"executor.bsh"就是你所谓的"父"脚本.

// executor.bsh

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

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

x = new HelloWorld();
x.start();
Run Code Online (Sandbox Code Playgroud)

第二个文件包含脚本类.请注意,我使用的是Scripted Command,根据BeanShell文档,文件名必须与命令名相同.

// source.bsh

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

    }
}
Run Code Online (Sandbox Code Playgroud)

我在java类中调用executor.bsh:

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);
Run Code Online (Sandbox Code Playgroud)

请注意,我留下了一些注释代码,这些代码也显示我使用Reflection从Java执行脚本类.这就是结果:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Run Code Online (Sandbox Code Playgroud)