打开dos窗口,键入:java bsh.Console命令
出现BeanShell图片代表设置成功,BeanShell开始运行
1)在Eclipse中建立工程TestBeanShell
2)添加所需Java类文件建立ServiceContext.java,此文件记录一个复杂Java类对象。
3)BeanShell方法实现详解
//Person.java package bhs.shell; public class Person { private String pname; public Person(){ super(); } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } } //ServiceContext.java package bhs.shell; import java.util.HashMap; import java.util.Map; public class ServiceContext { public static final String EVENT_ID = "EVENT_ID"; public static final String MESSAGE_ID = "MESSAGE_ID"; private Map<String, Object> context = new HashMap<String, Object>(); public void setAttribute(String key, Object value) { context.put(key, value); } public Object getAttribute(String key) { return context.get(key); } public void removeAttribute(String key) { context.remove(key); } } //Bsh1.java package bhs.shell; import java.util.*; import bsh.EvalError; import bsh.Interpreter; import bsh.UtilEvalError; public class Bsh1 { public static void main(String[] args) throws EvalError, UtilEvalError { Bsh1.testBshSimpleType(); Bsh1.testBshComplexType(); Bsh1.testBshComplexExpression(); } public static boolean testBshSimpleType() throws EvalError { Interpreter i = new Interpreter(); // Construct an interpreter Boolean flag = false; i.set("input", 3); i.set("b", 7); // Eval a statement and get the result flag = (Boolean) i.eval("b > input"); System.out.print("Simple Type result: "+flag+"\n"); return flag; } public static boolean testBshComplexType()throws EvalError, UtilEvalError { ServiceContext context = new ServiceContext(); List<Person> list= new ArrayList<Person>(); Person p1=new Person(); p1.setPname("eva"); Person p2=new Person(); p2.setPname("jason"); list.add(p1); list.add(p2); context.setAttribute("input", list); Boolean flag = false; flag=(Boolean)validateCondition("((Person)context.getAttribute(\"input\").get(1)).getPname().equals(\"jason\")", context); System.out.print("Complex Type result: "+flag+"\n"); return flag; } public static boolean testBshComplexExpression()throws EvalError, UtilEvalError{ ServiceContext context = new ServiceContext(); context.setAttribute("a", 3); context.setAttribute("b", 4); context.setAttribute("c", 6); context.setAttribute("d", null); Boolean flag = false; flag=(Boolean) validateCondition("((int)context.getAttribute(\"a\")<(int)context.getAttribute(\"b\"))&&(context.getAttribute(\"d\")==null)",context); System.out.print("Complex Expression result: "+flag+"\n"); return flag; } public static boolean validateCondition(String condition, ServiceContext context) throws EvalError, UtilEvalError{ Interpreter i = new Interpreter();// construct an Interpreter Boolean flag = false;// record the result expression estimated i.getNameSpace().importPackage("bhs.shell");// import whole package or import special class with "importClass(Person.class.getName())" i.set("context", context); flag = (Boolean) i.eval(condition); return flag; } }