今天在项目里面看到了前人用到了一个很有用的工具java beanshell(bsh),网上搜罗了一番,发现挺有用的,于是乎,赶紧记下来备忘。
下载地址:http://www.beanshell.org/download.html(就是一个jar包)
doc:http://www.beanshell.org/manual/bshmanual.html
Beanshell是用Java写成的,一个小型的、免费的、可以下载的、嵌入式的Java源代码解释器,具有对象脚本语言特性。BeanShell执行标准Java语句和表达式,另外包括一些脚本命令和语法。利用的原理当然是java的反射。
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" |
和java类似
which命令会列出指定类在哪个jar包中,很有用啊:
bsh % which( java.lang.String );
Jar: file:/usr/java/j2sdk1.4.0/jre/lib/rt.jar
默认已经导入下列包:
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还是挺强大的,若要详细了解,还是到上面说的官网里面看吧,很详细的。