java bsh_java命令解释器介绍-bsh

今天在项目里面看到了前人用到了一个很有用的工具java beanshell(bsh),网上搜罗了一番,发现挺有用的,于是乎,赶紧记下来备忘。

Beanshell是用Java写成的,一个小型的、免费的、可以下载的、嵌入式的Java源代码解释器,具有对象脚本语言特性。BeanShell执行标准Java语句和表达式,另外包括一些脚本命令和语法。利用的原理当然是java的反射。

Quick Start

java bsh.Console // run the graphical desktop or java bsh.Interpreter // run as text-only on the command line or java bsh.Interpreter filename [ args ] // run script file

第一种即为有界面的运行,但我在win7里面运行不了(server03中可以)

第二站为命令行方式运行

第三种即直接运行一个脚本。

但在项目里面用,还是先把这个jar包放在项目classpath里面,然后再代码里面用下面方式运行: import bsh.Interpreter; Interpreter i = new Interpreter(); // Construct an interpreter i.set("foo", 5); // Set variables i.set("date", new Date() ); Date date = (Date)i.get("date"); // retrieve a variable // Eval a statement and get the result i.eval("bar = foo*10"); System.out.println( i.get("bar") ); // Source an external script file i.source("somefile.bsh");

简单实例

其实语法和java类似,另外还支持类似于js一样的若变量类型,具体看实例:

例一: foo = "Foo"; four = (2 + 2)*2/2; print( foo + " = " + four ); // print() is a BeanShell command // Do a loop for (i=0; i<5; i++) print(i); // Pop up a frame with a button in it button = new JButton( "My Button" ); frame = new JFrame( "My Frame" ); frame.getContentPane().add( button, "Center" ); frame.pack(); frame.setVisible(true);

例二: int addTwoNumbers( int a, int b ) { return a + b; } sum = addTwoNumbers( 5, 7 ); // 12

例三: add( a, b ) { return a + b; } foo = add(1, 2); // 3 foo = add("Oh", " baby"); // "Oh baby"

内置有用的命令 source(), run() - Read a bsh script into this interpreter, or run it in a new interpreter

frame() - Display a GUI component in a Frame or JFrame.

load(), save() - Load or save serializable objects to a file.

cd(), cat(), dir(), pwd(), etc. - Unix-like shell commands

exec() - Run a native application

javap() - Print the methods and fields of an object, similar to the output of the Java javap command.

setAccessibility() - Turn on unrestricted access to private and protected components.

类的导入

和java类似

which命令会列出指定类在哪个jar包中,很有用啊: bsh % which( java.lang.String ); Jar: file:/usr/java/j2sdk1.4.0/jre/lib/rt.jar

默认已经导入下列包: javax.swing.event

javax.swing

java.awt.event

java.awt

java.net

java.util

java.io

java.lang

bsh.EvalError

bsh.Interpreter

importCommands("/bsh/commands");

通过上面方式可以导入自己写的脚本,在别的脚本里面可以直接调用呦。

The following commands manipulate or access the classpath:addClassPath(), setClassPath(), getClassPath() Modify the BeanShell classpath.

reloadClasses() Reload a class or group of classes.

getClass() Load a class explicitly taking into account the BeanShell classpath.

getResource() Get a resource from the classpath.

总之,bsh还是挺强大的,若要详细了解,还是到上面说的官网里面看吧,很详细的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值