بیشترلیست موضوعات • Index • ExamplesApache Jakarta and Beyond: A Java Programmers Introduction By
Larne Pekowsky Publisher : Addison Wesley Professional Pub Date : December 30, 2004 ISBN : 0-321-23771-4 Pages : 608
توضیحاتافزودن یادداشت جدید
16.6. Calling BeanShell from Java
Just as it is possible to invoke Java from BeanShell, it is possible to call out to BeanShell scripts from within Java code. The key to this is the Interpreter class. A program may create multiple instances of Interpreter; each will have its own namespace and act independently of the others.Interpreter has four methods of immediate interest. set() sets a new value in the top-level namespace and correspondingly get() returns a value from this namespace. eval() is a catch-all method that takes a string representing any valid BeanShell expression or definition and processes it just as if it had been typed in the interactive interpreter. Finally, source() takes the name of a file and evaluates all the expressions in that file. These methods are all demonstrated in the next example:
import bsh.Interpreter; public class Demo1 { public static void main(String args[]) { Interpreter intrp = new Interpreter(); intrp.set("aValue", 5); System.out.println(intrp.get("aValue")); intrp.set("calc",new Calc()); System.out.println(interp.eval("calc.add(aValue,3)")); interp.eval("addOne(x) {x+1;}"); interp.eval("value2 = addOne(9)"); System.out.println(intrp.get("value2")); intrp.source("sample.bsh"); System.out.println(intrp.get("thirdValue")); System.out.println(interp.eval("addTwo(4)")); } }
If sample.bsh contains the following lines
thirdValue = 109; addTwo(x) {x+2;}
then when Demo1 is run it will produce the following output:
5 8 10 109 6
Note in particular how the assignment of value2, which occurred in an eval(), is nonetheless available from a call to get().As a final exercise in self-reference, note that Demo1 could be invoked from BeanShell or even created within a BeanShell sessioninterpreters calling interpreters ad infinitum.