Beanshell 调用自己的方法

BeanShell 是一个小的,免费的,可以内嵌的java源代码解释器,它具有面向对象脚本语言的特性,并且是用java实现的。Beanshell 可以动态地执行标准的java语句,还自带简单的脚本命令和语法。

 

Beanshell 的一个重要用途就是:通过建立一个BeanShell解释器,使用eval()或source()命令,你可以在你的应用程序中求文本表达式的值和运行脚本。就像matlab中的eval()函数一样。

 

例如:

Interpeter bsh = new Interpreter();

// Evaluate statements and expressions
bsh.eval("foo=Math.sin(0.5)");
bsh.eval("bar=foo*5; bar=Math.cos(bar);");
bsh.eval("for(i=0; i<10; i++) { print(/"hello/"); }");
// same as above using java syntax and apis only
bsh.eval("for(int i=0; i<10; i++) { System.out.println(/"hello/"); }");

//Source from files or streams
bsh.source("myscript.bsh");  // or bsh.eval("source(/"myscript.bsh/")");

// Use set() and get() to pass objects in and out of variables
bsh.set( "date", new Date() );
Date date = (Date)bsh.get( "date" );
// This would also work:
Date date = (Date)bsh.eval( "date" );

bsh.eval("year = date.getYear()");
Integer year = (Integer)bsh.get("year");  // primitives use wrappers

 

然而在前几天的一个应用中我在一个类中预先实现了一些方法,我需要通过读一个文件来决定到底该调用哪个方法,文件中保存着方法的名字。于是我用了类似于以下的语句:

import bsh.Interpreter;

public class Main {

    public String str = "hello interpreter";

    public static void main(String[] args)

    {
        Main mainObj = new Main();
        mainObj.doProcess();
    }

    public void doProcess()
    {

        Interpreter bshInterpreter = new Interpreter();

        try {

            bshInterpreter.eval("printText()");

        } catch (bsh.EvalError ee) {
            System.out.println(ee.toString());
        }
    }

 

    private void printText()
    {
        System.out.println(str);
    }

}

 

但是报错说找不到printText()方法;

Sourced file: inline evaluation of: "printText();'' : Command not found: printText()

 

改进的方法是:

1. private void printText() 需要改为public

2. bshInterpreter.eval("printText()"); 改为

    bshInterpreter.set("thisObject", this);    // 将this object 赋给变量thisObject

    bshInterpreter.eval("thisObject."+"printText()");  // this.printText()

 

 

21-04-2010, Stavanger

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值