我正在嘗試在Android的Java應用程序中使用Mozilla Rhino來評估一些JavaScript。我正在使用Eclipse + ADT插件。在Android上使用Rhino的問題
首先,我嘗試從Mozilla網站下載Rhino .jar文件,並將其作爲Eclipse中的庫添加到項目中。 Eclipse認可它並編譯應用程序。但是,運行它時,我會在調用Context.evaluateReader()
時收到異常(請參閱下面的堆棧跟蹤)。
然後我嘗試在Eclipse中添加Rhino源代碼作爲一個單獨的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
我的代碼擊中了例外位看起來是這樣的:
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) {
// ...
}
我還發現this blog post包含類似的代碼,並說有用。作者說他使用了一個來自Android Scripting網站的jar文件。我在那裏發現的唯一jar文件在rhino_extras_r3.zip
。但是,它不包含.class
文件,而是包含classes.dex
文件。當我在Eclipse中將它添加爲庫時,它不能識別它包含的類,因此無法編譯我的項目,因爲缺少對Rhino類的引用。
任何有關如何讓這個工作的幫助,感激不盡!
默認情況下,Rhino會嘗試生成JVM字節碼,作爲一種Javascript JIT。這很酷,但是Android不運行JVM字節碼 - 它運行Dalvik字節碼。因此,您必須通過您顯示的代碼片段來禁用優化,以允許Rhino運行。 – CommonsWare 2010-10-04 22:06:48
我確認這有助於:-) – agibalov 2012-07-24 10:33:11
@仍然面對同樣的問題後添加此行.. – 2012-10-27 12:39:10