在Java应用中使用BeanShell(2.0b41)的简单示例

来源:互联网 发布:finale2016打谱软件 编辑:程序博客网 时间:2024/06/05 00:17

1. 在工程中导入jar包:bsh-2.0b4.jar


2. 示例代码:

package com.huey.dream.bsh;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Date;import bsh.EvalError;import bsh.Interpreter;/** * 使用BeanShell的简单示例 * @author  huey * @version 1.0  * @created 2014-11-14 */public class BshApp {public static void main(String[] args) {// 创建一个bsh脚本解释器Interpreter interpreter = new Interpreter();try {interpreter.eval("which(java.lang.String);");// 设置变量,然后执行bsh脚本interpreter.set("date", new Date());interpreter.eval("print(date)");// 执行bsh脚本,然后获取变量interpreter.eval("foo = \"Hello World\"");String foo = (String) interpreter.get("foo");System.out.println(foo);// 加载脚本文件并执行boolean result = (Boolean) interpreter.source("src/hello.bsh");System.out.println(result);} catch (EvalError e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

3. 脚本文件hello.bsh:

add(a, b) {return a + b;}print(add(1, 2));print(add("Bean", "Shell"));return true;



0 0
原创粉丝点击