您的位置:首页 > 运维架构 > Shell

Shell_BeanShell快速入门---Java应用程序脚本引擎

2012-04-12 14:07 495 查看

下载和运行BeanShell

请到http://www.beanshell.org下载最新的JAR文件。你可以用图形桌面模式和命令行模式起动BeanShell。

如果你只是要玩一玩BeanShell,你可以在BeanShell的jar文件上双击来起动BeanShell的桌面。但不管怎样,如果你要让BeanShell与你的类与应用程序一起工作就必须将BeanShell的jar文件加到classpath中。

你可以将BeanShell的jar文件拖到JAVA_HOME的ext目录也可以直接加到classpath中。

·        windows用户请将bsh.jar放在JAVA_HOME/jre/lib/ext文件夹,OSX用户可以放在/Library/Java/Extensions.
或者增加BeanShell到你的classpath目录,如:

unix: export CLASSPATH=$CLASSPATH:bsh-xx.jar

windows:set classpath %classpath%;bsh-xx.jar

然后你就可以运行BeanShell在GUI或命令行模式:

·         javabsh.Console       // run the graphical desktop

or

     java bsh.Interpreter   // run as text-onlyon the command line

or

     java bsh.Interpreter filename [ args ] // run scriptfile

可以在你的应用程序内部来运行,也可以作为debug及servlet的远程服务器模式,或一个Applet内部来运行BeanShell。请参考"BeanShellModes of Operation"获得更多详情。

完整代码:

package cn.com.sparknet.util;

import bsh.*;

import java.util.*;

public class BeanShell {

public static void main(String[] args) {

try {

Interpreter interpreter = new Interpreter(); // 构造一个解释器

interpreter.set("foo", 5); // 设置变量

interpreter.set("date", new Date()); //设置一个时间对象

Date date = (Date) interpreter.get("date"); // 重新得到时间变量

interpreter.println(date.toString()); //打印时间变量

interpreter.eval("bar = foo*10"); // 对一段脚本求值,并得到结果

System.out.println(interpreter.get("bar")); //打印变量

interpreter.source("d:\\helloWorld.bsh"); // 导入并执行一个脚本文件

}

catch (Exception e) {

//如果发生异常,写入日志文件

Log.error(new BeanShell(), "main", FormatDate.getCurrDate(),e.getMessage());

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息