【发布时间】:2015-04-10 13:57:26
【问题描述】:
我想从 Java 代码中格式化一些 json 文件,并且我想使用著名的http://jsbeautifier.org 库。
我关注了这个问题:Call external javascript functions from java code,但找不到要调用的正确函数。
我试过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"
有什么问题吗?
【问题讨论】:
-
您是否正确加载了
js_beautify库?显示一些代码。 -
@Stephan 谢谢,但这不是这个问题的重复问题。这个问题的重点是如何在 Java/Scala 代码中调用该库,而不是如何从命令行调用它。
标签: java javascript scala js-beautify