2011-06-14 69 views
2

如何從groovy中獲得執行的JavaScript代碼的結果?我嘗試了以下,但我總是找回字符串「世界」。我會期待一個對象或地圖。如何從groovy執行Javascript代碼並將結果作爲地圖顯示?

import javax.script.ScriptEngineManager 
import javax.script.SimpleBindings 

def manager = new ScriptEngineManager() 
manager.getEngineByName("JavaScript").eval(""" 
    {hello: name} 
""", [name:'world'] as SimpleBindings) 

回答

2

簡單!

您可以在對象映射到一個變量,返回......

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 Map對象,並更新......

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

+0

我接受這個,因爲這比使用內部類更好。 – Blacktiger 2016-12-13 13:58:51

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] 

隱而不宣」我覺得這是一種非常乾淨的做事方式(如果你有一個陣列地圖,可能需要一些工作)

但我能找到的最好的: -/

+0

我曾經以爲從Java運行Javascript應該很容易,但我猜不是。好吧。 – Blacktiger 2011-06-15 19:12:33