在Android上使用Rhino的问题

Liq*_*ire 18 java android rhino

我正在尝试在Android的Java应用程序中使用Mozilla Rhino来评估一些JavaScript.我正在使用Eclipse + ADT插件.

首先,我尝试从Mozilla的网站下载Rhino .jar文件,并将其作为Eclipse中的库添加到项目中.Eclipse认识到它很好并编译了应用程序.但是,在运行它时,我在调用时会遇到异常Context.evaluateReader()(请参阅下面的堆栈跟踪).

然后我尝试将Rhino源代码添加为Eclipse中的单独Android项目,将其标记为库并在我的项目中引用它,这足以让Eclipse将其编译,但导致了同样的错误.

这是我得到的堆栈跟踪(java.lang.UnsupportedOperationException: can't load this type of class file)

Thread [<7> Thread-8] (Suspended (exception UnsupportedOperationException)) 
    DefiningClassLoader(ClassLoader).defineClass(String, byte[], int, int, ProtectionDomain) line: 338  
    DefiningClassLoader.defineClass(String, byte[]) line: 62    
    Codegen.defineClass(Object, Object) line: 159   
    Codegen.createScriptObject(Object, Object) line: 114    
    Context.compileImpl(Scriptable, Reader, String, String, int, Object, boolean, Evaluator, ErrorReporter) line: 2440  
    Context.compileReader(Reader, String, int, Object) line: 1326   
    Context.compileReader(Scriptable, Reader, String, int, Object) line: 1298   
    Context.evaluateReader(Scriptable, Reader, String, int, Object) line: 1137  
    TimetableProcessor.evaluate(InputStream, String, String[]) line: 31 
    TimetableProcessor.processBasicData(InputStream, String) line: 58   
    TimetableProcessor.process(InputStream, String) line: 52    
    TimetableUpdater.update() line: 53  
    Main$1$1.run() line: 22
Run Code Online (Sandbox Code Playgroud)

我遇到异常的代码看起来像这样:

        Context cx = Context.enter();
        cx.setLanguageVersion(Context.VERSION_1_7);
        Scriptable scope = cx.initStandardObjects();
        try {
            Object result = cx.evaluateReader(scope, new InputStreamReader(data), /* <<< exception here */
                    filename, 0, null);
        } catch (IOException e) {
            // ...
        }
Run Code Online (Sandbox Code Playgroud)

我还发现这篇博文包含类似的代码并说它有效.作者说他使用了Android Scripting网站上的jar文件.我找到的唯一的jar文件是在rhino_extras_r3.zip.但是,它不包含.class文件,而是包含classes.dex文件.当我在Eclipse中将其添加为库时,它无法识别它包含的类,因此无法编译我的项目,因为缺少对Rhino类的引用.

任何有关如何使其工作的帮助表示赞赏!

Liq*_*ire 34

我终于开始工作了.我应该更加关注我链接的博文.

如果我添加该行

cx.setOptimizationLevel(-1);
Run Code Online (Sandbox Code Playgroud)

为了禁用优化,一切都很完美.

  • 默认情况下,Rhino尝试动态生成JVM字节码,作为一种Javascript JIT.这很酷,但Android不运行JVM字节码 - 它运行Dalvik字节码.因此,您必须通过您显示的代码段禁用优化,以允许Rhino运行. (13认同)

Com*_*are 11

在版本控制系统中,SL4A站点rhino1_7R2.jar上提供了Android兼容版本.这是一个示例项目,它将Rhino和BeanShell包装到Android解释器服务中.