BeanShell

1.简介

     BeanShell是一个Java脚本语言,官网地址https://github.com/beanshell/beanshell/

     在XWorker中常用的脚本语言是Groovy,Beanhell不是很常用。BeanShell可以运行在Android中,而Groovy不行,因为Groovy需要编译成类,而BeanShell不需要。

2.设计思路

     BeanShell模型比较简单,就是实现run方法,模型作为动作。

     run方法的Java代码如下:

public static Object run(ActionContext actionContext) throws EvalError {
		Bindings bindings = actionContext.getScope(actionContext.getScopesSize() - 2);		
		
		World world = bindings.world;
		Action action = null;
		if(bindings.getCaller() instanceof Thing){
			Thing actionThing = (Thing) bindings.getCaller();
			action = actionThing.getAction();
		}else{
			action = (Action) bindings.getCaller();
		}
		
		if(action == null){
			return null;
		}
		
		Interpreter i = new Interpreter();
		i.set("ac", actionContext);
		i.set("actionContext", actionContext);;
		i.set("world", world);
		
		if(action.getThing().getBoolean("mergeActionContext")) {
			for(String key : actionContext.keySet()) {
				i.set(key, actionContext.get(key));
			}
		}
		
		String code = action.getThing().getStringBlankAsNull("code");
		if(code == null || "".equals(code)) {
			return null;
		}else {
			return i.eval(code);
		}
	}

3.示例

<?xml version='1.0' encoding='utf-8'?>

<BeanShellAction name="BeanShellAction" descriptors="xworker.beanshell.BeanShellAction">
    <code><![CDATA[import java.util.Date;

Date date = new Date();
System.out.println(date);

return date;]]></code>
</BeanShellAction>

 

Copyright ©  2007-2019 XWorker.org  版权所有  沪ICP备08000575号