Tree计算器是对Tree结构节点进行抽象计算的程序.
利用BeanShell实现应用逻辑,以获取灵活性和适应性。
主程序采用Java实现。
需要:
。Java调用BeanShell脚本
。BeanShell可以访问Java程序的对象
BeanShell实现具体的算法:
。对节点进行计算,如根据节点的某些属性值,在Tree中的位置等数据计算
。实现一个Calculator接口:
2个方法
---int filter(Node node); ///< 节点过滤检查
---void calc(Node); ///< 实际计算
Calculator实现需要访问Node之外的以下信息:
.Tree对象
.全局配置
读或者修改Java程序的对象的信息。
以下2个示例是验证实现方法和demo代码。
BeanShell的开发手册见:
http://www.beanshell.org/manual/bshmanual.html
示例1:
Java调用BeanShell实现的接口
static_calculator.bsh
import com.example.demo.beanshell.Node;
int filter(Node node) {
return 1;
}
void calc(Node node) {
print("calc end");
}
Java代码:
Interpreter i = new Interpreter();
i.source("static_calculator.bsh");
Calculator calculator = (Calculator) i.getInterface(Calculator.class);
Node node = new Node();
node.setId(1);
log.info("filter return value:{}",calculator.filter(node));
calculator.calc(node);
示例2:
BeanShell访问和修改Java程序的对象.
dynamic_calculator.bsh
import com.example.demo.beanshell.Node;
import com.example.demo.beanshell.Tree;
Tree tree;
int filter(Node node) {
return 1;
}
void calc(Node node) {
node.setId(123);
print("tree childNumber="+tree.getChildNumber());
print("calc end");
}
Java代码:
Interpreter i = new Interpreter();
i.source("dynamic_calculator.bsh");
Tree tree = new Tree();
tree.add(new Node(100));
i.set("tree",tree);
Calculator calculator = (Calculator) i.getInterface(Calculator.class);
Node node = new Node(1);
log.info("filter return value:{}",calculator.filter(node));
calculator.calc(node);
log.info(node.toString()); ///< node的内容在bsh中修改为123.
相关代码:
Calculator.java
package com.example.demo.beanshell;
public interface Calculator {
int filter(Node node);
void calc(Node node);
}
Node.java
package com.example.demo.beanshell;
import lombok.Data;
@Data
public class Node {
private Integer id;
private Short level;
public Node(Integer id) {
this.id = id;
}
}
Tree.java
package com.example.demo.beanshell;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Tree {
private List<Node> children = new ArrayList();
public void add(Node node) {
children.add(node);
}
public int getChildNumber() {
return children.size();
}
}