栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Rhino让java执行javascript的方法实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Rhino让java执行javascript的方法实例

下载Rhino https://developer.mozilla.org/en-US/docs/Rhino

把js.jar拷贝到项目工程

实现从Java中执行js中的函数、从js中调用Java中的方法,代码:

复制代码 代码如下:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView text1 = (TextView) findViewById(android.R.id.text1);
        TextView text2 = (TextView) findViewById(android.R.id.text2);

        text1.setText(runscript(JAVA_CALL_JS_FUNCTION, "Test", new String[] {}));

        text2.setText(runscript(JS_CALL_JAVA_FUNCTION, "Test", new String[] {}));
    }

   
    private static final String JAVA_CALL_JS_FUNCTION = "function Test(){ return '农民伯伯 java call js Rhino'; }";

   
    private static final String JS_CALL_JAVA_FUNCTION = //
    "var scriptAPI = java.lang.Class.forName("" + MainActivity.class.getName() + "", true, javaLoader);" + //
        "var methodRead = scriptAPI.getMethod("jsCallJava", [java.lang.String]);" + //
        "function jsCallJava(url) {return methodRead.invoke(null, url);}" + //
        "function Test(){ return jsCallJava(); }";

   
    public String runscript(String js, String functionName, Object[] functionParams) {
        Context rhino = Context.enter();
        rhino.setOptimizationLevel(-1);
        try {
            scriptable scope = rhino.initStandardObjects();

            scriptableObject.putProperty(scope, "javaContext", Context.javaToJS(MainActivity.this, scope));
            scriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(MainActivity.class.getClassLoader(), scope));

            rhino.evaluateString(scope, js, "MainActivity", 1, null);

            Function function = (Function) scope.get(functionName, scope);

            Object result = function.call(rhino, scope, scope, functionParams);
            if (result instanceof String) {
                return (String) result;
            } else if (result instanceof NativeJavaObject) {
                return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
            } else if (result instanceof NativeObject) {
                return (String) ((NativeObject) result).getDefaultValue(String.class);
            }
            return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
        } finally {
            Context.exit();
        }
    }

    public static String jsCallJava(String url) {
        return "农民伯伯 js call Java Rhino";
    }
}

注意,混淆的时候js.jar可能混淆不过去,请参照文章4.1的方法。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152783.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号