Apache Jakarta and Beyond: A Java Programmeramp;#039;s Introduction [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Apache Jakarta and Beyond: A Java Programmeramp;#039;s Introduction [Electronic resources] - نسخه متنی

Larne Pekowsky

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







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.


/ 207