[英]How to call jsbeautifier from Java/scala?
我想從Java代碼格式化一些json文件,並且想使用著名的http://jsbeautifier.org庫。
我遵循了這個問題: 從Java代碼調用外部javascript函數 ,但是找不到正確的函數來調用。
我嘗試了inv.invokeFunction("js_beautify", json)
,但報告:
java.lang.NoSuchMethodException: no such method: js_beautify
我的代碼(實際上是Scala,但僅使用Java API):
val manager = new ScriptEngineManager()
val engine = manager.getEngineByName("JavaScript")
// read script file
engine.eval(FileUtils.readFileToString(new File("beautify.js")))
val inv = engine.asInstanceOf[Invocable]
// call function from script file
inv.invokeFunction("js_beautify", json).asInstanceOf[String]
文件beautify.js
的結構為:
(function() {
// a lot of js code
// ...
if (typeof define === "function" && define.amd) {
// Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
define([], function() {
return { js_beautify: js_beautify };
});
} else if (typeof exports !== "undefined") {
// Add support for CommonJS. Just put this file somewhere on your require.paths
// and you will be able to `var js_beautify = require("beautify").js_beautify`.
exports.js_beautify = js_beautify;
} else if (typeof window !== "undefined") {
// If we're running a web page and don't have either of the above, add our one global
window.js_beautify = js_beautify;
} else if (typeof global !== "undefined") {
// If we don't even have window, try global.
global.js_beautify = js_beautify;
}
}());
也許我需要從Java提供一些global
或window
上下文?
更新:
我遵循了@tiblu的回答中的“ JSBeautify NetBeans插件”:
class FormatJson {
def apply(json: String): String = {
val context = Context.enter()
context.setLanguageVersion(Context.VERSION_1_6)
val scope = context.initStandardObjects()
val reader = new FileReader(new File("beautify.js"))
context.evaluateReader(scope, reader, "Beautify", 1, null)
val fct = scope.get("js_beautify", scope).asInstanceOf[org.mozilla.javascript.Function]
fct.call(context, scope, scope, Array[AnyRef](json)).toString
}
}
但它報告:
Exception in thread "main" java.lang.ClassCastException: org.mozilla.javascript.UniqueTag cannot be cast to org.mozilla.javascript.Function
並且scope.get("js_beautify", scope)
實際上是NOT_FOUND
。
我正在使用"org.mozilla" % "rhino" % "1.7R5"
有什么問題嗎?
看看JSBeautify NetBeans插件是如何用Java編寫的-https: //github.com/drewhamlett/netbeans-jsbeautify/tree/master/src/com/drewhamlett/jsbeautify
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.