CallingJavaScriptFunctions |
|
|
public class CallingJavaScriptFunctions {
public static void main(String[] args) throws ScriptException, IOException {
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
InputStream in = ClassLoader.getSystemResourceAsStream("js/functions.js");
LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
String script = "";
String line = "";
while((line = reader.readLine()) != null) {
script += line;
}
cx.evaluateString(scope, script,"MySource", 1, null);
//获取方法
Object object = scope.get("a", scope);
if (object == Scriptable.NOT_FOUND) {
System.out.println("a is not defined.");
} else {
System.out.println("a = " + Context.toString(object));
}
if (!(object instanceof Function)) {
System.out.println("f is undefined or not a function.");
} else {
Object functionArgs[] = { "zhangsan" };
Function f = (Function)object;
Object result = f.call(cx, scope, scope, functionArgs);
String report = Context.toString(result);
System.out.println(report);
}
} finally {
Context.exit();
}
}
}
|
AddVariableInJavaScript |
|
|
public class AddVariableInJavaScript {
/**
* @param args
*/
public static void main(String[] args) {
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
// Add a global variable "out" that is a JavaScript reflection
// of System.out
Object jsOut = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", jsOut);
String s = "out.println(42)";
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(Context.toString(result));
} finally {
Context.exit();
}
}
}
|
AccessingJavaBeanProperties |
|
|
public class AccessingJavaBeanProperties {
/**
* @param args
*/
public static void main(String[] args) {
Context cx = Context.enter();
try {
Scriptable scope = new ImporterTopLevel(cx);
InputStream in = ClassLoader.getSystemResourceAsStream("js/access_javabean_property.js");
LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
String script = "";
String line = "";
while((line = reader.readLine()) != null) {
script += line;
}
cx.evaluateString(scope, script,"MySource", 1, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Context.exit();
}
}
}
|
PutJavaVariableInScope |
|
|
public class PutJavaVariableInScope {
/**
* @param args
*/
public static void main(String[] args) {
Context ctx = Context.enter(); //获取环境设置
Scriptable scope = ctx.initStandardObjects(); //初始化本地对象
scope.put("x", scope, new Integer(20)); //输入参数设置
scope.put("y", scope, new Integer(30));
try {
ctx.evaluateString(scope, "var result=x+y", "", 1, null); //执行
System.out.println(scope.get("result", scope)); //结果输出
} finally {
Context.exit();
}
}
}
|