Rhino| Rhino的测试例子

来源:互联网 发布:java后端需要学node吗 编辑:程序博客网 时间:2024/05/21 17:43

testAll.js

var jsVar = "jsVarValue";var nullVal = null;var myDate = new java.util.Date();// 在JS中使用原生的Java对象.var stuName = student.getName();// 在JS中可以直接调用java对象的方法.var jsonData = {    a : 1,    b : [ 'x', 'y' ]};function showHello() {    return "hello!";}function countNumber(aaa) {    return aaa;}java.lang.System.out.println("你好");100 + 2;// 直接运行的JS代码就会当做结果直接输出.

testLoadJs.js

var name = "Yves";function countNumber(aaa) {    return aaa;}

Student.java

/**    * Filename:    Student.java    * Copyright:   Copyright (c)2016   * Company:     Yves   * @version:    1.0     * Create at:   2017-8-3 下午4:53:25    * Description:   * * Author       Yves He  */package cn.com.yves;public class Student {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String showInfo() {        return "name: " + this.name + "\t" + "age:" + this.age;    }    public String showInfo(String hobby) {        return "name: " + this.name + "\t" + "age:" + this.age + "\t" + "hobby:" + hobby;    }}

TestAll.java

/**    * Filename:    TestAll.java    * Copyright:   Copyright (c)2016   * Company:     Yves   * @version:    1.0     * Create at:   2017-8-3 下午4:52:05    * Description:   * * Author       Yves He  */package cn.com.yves;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.LineNumberReader;import java.util.Date;import sun.org.mozilla.javascript.internal.Context;import sun.org.mozilla.javascript.internal.Function;import sun.org.mozilla.javascript.internal.Scriptable;import sun.org.mozilla.javascript.internal.ScriptableObject;/** * JDK版本:1.7 *  * 无需引用js.jar,Rhino集成在JDK1.6以及上的JDK中. *  * @author Yves He *  */public class TestAll {    public static void main(String[] args) {        testAll();        /**         * 显示结果:         *          * 10010         */        // testLoadJSFile();        /**         * 显示结果:         *          * 10010         */        // testLoadJSFile2();        /**         * 显示结果:         *          * 你好         */        // testCallJavaInScript();// 你好        /**         * 显示结果:         *          * name: Yves age:23         *          * name: Yves age:23 hobby:study         */        // testCallJavaInScript2();        /**         * 显示结果:         *          * name is Yves!         */        // testCallScriptInJava();        /**         * 显示结果:         *          * hello Yves!         */        // testCallScriptInJava2();    }    /**     * 综合例子     */    public static void testAll() {        String jsFileName = "testAll.js";        FileReader fileReader = null;        Context context = Context.enter();        try {            String filename = System.getProperty("user.dir") + File.separator + jsFileName;            fileReader = new FileReader(filename);            Scriptable scope = context.initStandardObjects();            // 1.将java对象放置JS的作用域中            Student students = new Student();            students.setAge(23);            students.setName("yves");            Object jsObj = Context.javaToJS(students, scope);            // scope.put("student", scope, jsObj);            ScriptableObject.putProperty(scope, "student", jsObj);            // 2. load外部的js文件获取文件内容            // result 为执行JS产生的结果,如果JS中没有需要计算的表达式,结果为undefined            Object result = context.evaluateReader(scope, fileReader, "mysource", 1, null);            System.out.println("****JS文件运行的结果****\n" + result.getClass() + "\n" + Context.toString(result) + "\n");            System.out.println("****JS代码中调用JS方法:countNumber()****");            Object countNumberValve = context.evaluateString(scope, "countNumber(10010);", "mysource", 1, null);            System.out.println("\t " + Context.toString(countNumberValve) + "\n");            // 3.显示Scope中所有的对象(JS中定义的的方法和变量都是对象)            Object[] allObj = scope.getIds(); // 获取所有的方法和变量            System.out.println("***Scope中所有的对象(JS中定义的的方法和变量都是对象)的名称***");            for (Object o : allObj) {                System.out.println("\t\t" + o);            }            System.out.println();            // 4.对变量属性的操作            System.out.println("****对属性变量的操作***");            System.out.println("\t 对普通属性变量的操作");            Object nullVal = scope.get("nullVal", scope);            System.out.println("\t\t" + Context.toString(nullVal)); // toString将显示该对象js中的String值            Object jsVar = scope.get("jsVar", scope);            System.out.println("\t\t" + Context.toString(jsVar));            Object notFound = scope.get("notFound", scope);            System.out.println("\t\t" + Context.toString(notFound));            Object stuName = scope.get("stuName", scope);            System.out.println("\t\t" + Context.toString(stuName));            System.out.println("\t 对Json属性变量的操作");            Object jsonData = scope.get("jsonData", scope);            Object a = ((Scriptable) jsonData).get("a", (Scriptable) jsonData);            Scriptable b = (Scriptable) ((Scriptable) jsonData).get("b", (Scriptable) jsonData);            System.out.println("\t\t" + Context.toString(a));// 1            System.out.println("\t\t" + Context.toString(b.get(0, b)));// X            System.out.println("\t\t" + Context.toString(b.get(1, b)));// Y            System.out.println();            // 5.对方法的操作            System.out.println("****对方法的操作***");            System.out.println("\t 操作JS中原生的方法:showHello");            Object funObj = scope.get("showHello", scope);            if (!(funObj instanceof Function)) {                System.out.println("f is undefined or not a function.");            } else {                Function fun = (Function) funObj;                Object funResult = fun.call(context, scope, scope, new Object[] {});                System.out.println("\t\t" + Context.toString(funResult));            }            System.out.println("\t 操作Java对象中的方法:");            System.out.println("\t\t(直接在JS文件中操作即可.)");            System.out.println("\t 将JS中之前的Java对象还原出来后直接操作Java对象的方法");            Student oldStudent = (Student) Context.jsToJava(scope.get("student", scope), Student.class);            System.out.println("\t\t" + oldStudent.getAge());            System.out.println("\t 将JS中定义的Java对象获取后操作其方法");            Date myDate = (Date) Context.jsToJava(scope.get("myDate", scope), Date.class);            System.out.println("\t\t" + myDate.toString());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fileReader != null) {                try {                    fileReader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            Context.exit();        }    }    /**     * 加载Js文件(方式一)     */    public static void testLoadJSFile() {        Context context = Context.enter();        LineNumberReader reader = null;        try {            Scriptable scope = context.initStandardObjects();            String filename = System.getProperty("user.dir") + File.separator + "testLoadJs.js";            reader = new LineNumberReader(new FileReader(filename));            String temp = null;            StringBuffer sb = new StringBuffer();            while ((temp = reader.readLine()) != null) {                sb.append(temp).append("\n");            }            context.evaluateString(scope, sb.toString(), null, 1, null);            Object result = context.evaluateString(scope, "countNumber(10010);", "mysource", 1, null);            System.out.println(Context.toString(result));        } catch (Exception e) {            e.printStackTrace();        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            Context.exit();        }    }    /**     * 加载Js文件(方式二)     */    public static void testLoadJSFile2() {        Context context = Context.enter();        FileReader fileReader = null;        try {            Scriptable scope = context.initStandardObjects();            String filename = System.getProperty("user.dir") + File.separator + "testLoadJs.js";            fileReader = new FileReader(filename);            context.evaluateReader(scope, fileReader, null, 1, null);            Object result = context.evaluateString(scope, "countNumber(10010);", "mysource", 1, null);            System.out.println(Context.toString(result));        } catch (Exception e) {            e.printStackTrace();        } finally {            if (fileReader != null) {                try {                    fileReader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            Context.exit();        }    }    /**     * 在JS调用Java对象(在Js代码中声明Java对象)     */    public static void testCallJavaInScript() {        Context context = Context.enter();        try {            Scriptable scope = context.initStandardObjects();            context.evaluateString(scope, "java.lang.System.out.println('你好Yves!');", null, 1, null);        } catch (Exception e) {            e.printStackTrace();        } finally {            Context.exit();        }    }    /**     * 在JS调用Java对象(在java代码中声明Java对象)     */    public static void testCallJavaInScript2() {        Context context = Context.enter();        try {            Scriptable scope = context.initStandardObjects();            // 1.将java对象放置JS的作用域中            Student students = new Student();            students.setAge(23);            students.setName("Yves");            Object jsObj = Context.javaToJS(students, scope);            ScriptableObject.putProperty(scope, "student", jsObj);            // 2.在JS中调用放置在JS作用域中的Java对象.            Object result1 = context.evaluateString(scope, "student.showInfo()", null, 1, null);            Object result2 = context.evaluateString(scope, "student.showInfo('study')", null, 1, null);            System.out.println(Context.toString(result1));            System.out.println(Context.toString(result2));        } catch (Exception e) {            e.printStackTrace();        } finally {            Context.exit();        }    }    /**     * 在 Java 中调用 JavaScript 脚本中的变量     */    public static void testCallScriptInJava() {        Context context = Context.enter();        try {            Scriptable scope = context.initStandardObjects();            String jsStr = "var name = 'Yves';";            context.evaluateString(scope, jsStr, null, 1, null);            Object jsObject = scope.get("name", scope);            if (jsObject == Scriptable.NOT_FOUND) {                System.out.println("name is not defined.");            } else {                System.out.println("name is " + Context.toString(jsObject) + "!");            }        } catch (Exception e) {        } finally {            Context.exit();        }    }    /**     * 在Java中调用Script中的函数     */    public static void testCallScriptInJava2() {        Context context = Context.enter();        try {            Scriptable scope = context.initStandardObjects();            String jsStr = "function showHello(name) {return 'hello ' + name +'!';}";            context.evaluateString(scope, jsStr, null, 1, null);            Object functionObject = scope.get("showHello", scope);            if (!(functionObject instanceof Function)) {                System.out.println("showHello is undefined or not a function.");            } else {                Object args[] = { "Yves" };                Function test = (Function) functionObject;                Object result = test.call(context, scope, scope, args);                System.out.println(Context.toString(result));            }        } catch (Exception e) {        } finally {            Context.exit();        }    }}
原创粉丝点击