Beanshell介绍

来源:互联网 发布:java两个list集合合并 编辑:程序博客网 时间:2024/05/20 18:42
由于jbpm使用了beanshell作为其在jpdl中的脚本语言,所以特地看了一下beanshell这门脚本语言,看来以后确实还不错啊。下面是我这两天看的一些对于这门脚本语言的看法。
既然是特地为java设计的脚本语言,所以当然它与java有着很深的关系,有时候你甚至可以看作就是java的解释器。它的语法融合了java的严谨和脚本语言的方便和灵活,使得这门脚本语言可以象胶水一样用在如测试等地方,或者做快速的原型开发。它可以使用象java一样的强定义,也可以使用象脚本语言一样的弱定义,当然,两者会有一些不同(如作用域),但是大体上都是差不多的。好了,我们来看一个具体的实例:
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);
从上面的一些样例来看,beanshell是不用强类型定义的,解释器会自己在运行的时候自动加上相应的具体的类型。这个弱类型定义带来的一个好处就是可以不用重载函数而是直接使用了,如下面的例子:
add( a, b ) {
    
return a + b;
}


foo 
= add(12);            // 3
foo = add("Oh"" baby");   // "Oh baby"
beanshell中有一些关键字非常的有用,比如下面的this,它就可以返回一个具体的实例,从而实现如其他脚本语言中的闭包等功能。函数也是可以嵌套的。
foo() {
    print(
"foo");
    x
=5;

    bar() 
{
        print(
"bar");
    }


    
return this;
}


myfoo 
= foo();    // prints "foo"
print( myfoo.x ); // prints "5"
myfoo.bar();      // prints "bar"
更多的内容如作用域,接口定义,更多的关键字等还是看具体的用户手册吧,不多,估计在用的时候也够用了。

在jbpm的jpdl定义文件中,使用了beanshell作为其脚本语言来增强其功能,主要使用的地方包括decision节点决策,还有就是event中,比如下面简单的离子:
<process-definition>
  
<event type="node-enter">
    
<script>
      System.out.println("this script is entering node "+node);
    
</script>
  
</event>
  ...
</process-definition>
上面定义的结果就是在这个流程定义文件中所有的节点进入的时候会执行<script>包含下的语句,也就是打印一条信息。当在脚本中含有变量定义的时候,我们需要将其用<expression>将其包含起来,如下例:
<process-definition>
  
<event type="process-end">
    
<script>
      
<expression>
        a = b + c;
      
</expression>
      
<variable name='XXX' access='write' mapped-name='a' />
      
<variable name='YYY' access='read' mapped-name='b' />
      
<variable name='ZZZ' access='read' mapped-name='c' />
    
</script>
  
</event>
  ...
</process-definition>
在decision中,如果是比较简单的语句,也可以直接使用expression写在<decision>中,如下面:
[更正]下面的用法不是beanshell的语法,而是一种类jsp/jsf EL的表达式语言,具体可以参见expression,一些关于其的介绍可以参见 J2EE 入门。
   <decision name="decisionCheckingAndRawReport"
      expression
="#{varProjects.projectOfVirus.included}">
      
<transition name="true" to="procCheckingRawReport"/>
      
<transition name="false" to="join1"/>
   
</decision>
更多的相关的用法参考各自的用户手册吧。
beanshell的用户手册:http://www.beanshell.org/manual/contents.html
jbpm的用户手册:http://docs.jboss.com/jbpm/v3/userguide/