我可以实例化来自另一个 Beanshell 脚本的 beanshell 类吗? [英] Can I instantiate beanshell class sourced from another Beanshell script?

查看:68
本文介绍了我可以实例化来自另一个 Beanshell 脚本的 beanshell 类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 HelloW {
public void run(){
    print("Hello World");
}
}

应该运行和实例化类的主 beanshell 文件:

Main beanshell file which should run and instantiate class:

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

推荐答案

BeanShell 文档 在这方面做得很好,所以你应该先通读一遍.在您的情况下,问题很少.也就是说,有脚本对象.此外,您开始使用的 .bsh 文件需要执行脚本对象.以您的示例为例,此代码应该可以工作:

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

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

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

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

我相信,第一个executor.bsh"就是您所说的父"脚本.

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

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

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

    }
}

我在一个 java 类中调用了 executor.bsh:

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

请注意,我留下了一些注释代码,其中还显示了我使用反射从 Java 执行脚本类.这是结果:

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!

这篇关于我可以实例化来自另一个 Beanshell 脚本的 beanshell 类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆