如何从groovy获取执行的javascript代码的结果?我尝试了以下内容,但我总是回到字符串“世界”。我原本期望一个对象或地图。
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings
def manager = new ScriptEngineManager()
manager.getEngineByName("JavaScript").eval("""
{hello: name}
""", [name:'world'] as SimpleBindings)
答案 0 :(得分:3)
容易!
您可以将对象映射到变量,然后返回...
import javax.script.*
def bindings = [name:'world']
def response = new ScriptEngineManager()
.getEngineByName('javascript')
.eval("var r = {hello:name}; r;", bindings as SimpleBindings)
println response.hello // -> world
或者您可以跟踪response
地图对象,并更新...
import javax.script.*
def bindings = [name:'world',response:[:]]
new ScriptEngineManager()
.getEngineByName('javascript')
.eval("var r = {hello:name}; response.data = r;", bindings as SimpleBindings)
println bindings.response.data.hello // -> world
Groovy版本: 2.4.5
Java版本: 1.8.0_60
答案 1 :(得分:2)
这有点棘手(我能找到的唯一解决方案是使用内部sun.com
类): - /
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings
import sun.org.mozilla.javascript.internal.NativeObject
// A Category to parse NativeObject into a Map
class NativeObjectParser {
static Map asMap( NativeObject jsobj ) {
jsobj.allIds.inject( [:] ) { map, key ->
def value = jsobj.get( key, jsobj )
// Handle nested maps
map << [ (key):value instanceof NativeObject ? value.asMap() : value ]
}
}
}
// Your code as you had it before (apart from the JS defines a var, and returns that var object)
def manager = new ScriptEngineManager()
def ret = manager.getEngineByName("JavaScript").eval("""
var r = { 'hello': name }
r
""", [ name:'world' ] as SimpleBindings )
// Do the unwrapping
def map = use( NativeObjectParser ) {
ret.asMap()
}
println map
打印出来:
[hello:world]
感觉不是一种非常干净的做事方式(如果你有一个数组地图,可能需要一些工作)
但我能找到最好的: - /