验证BeanShell与Java交互方法

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();
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值