2012-02-15 47 views
1

我想在類方法調用期間動態地評估另一個函數的結果。但是,有和Eval的範圍問題。MissingMethodException嘗試在Eval中Groovy

class A { 
    private String a 
    public A() { 
     a = 5 
    } 

    public whatIsA() { 
     return a 
    } 


    public func() { 
     return "\\${whatIsA()}" 
    } 

    public test() { 
     return Eval.me("\"\${func()}\"") 
    } 
} 
def a = new A() 
a.test() 



Exception thrown: groovy.lang.MissingMethodException: No signature of method: Script1.func() is applicable for argument types:() values: {} 

groovy.lang.MissingMethodException: No signature of method: Script1.func() is applicable for argument types:() values: {} 
    at Script1.run(Script1.groovy:1) 
    at A.test(Script7:17) 
    at Script7.run(Script7:22) 

如何將A類實例的作用域傳遞給Eval腳本?

回答

2

試試這個嗎?

class A { 
    private String a 
    public A() { 
     a = 5 
    } 

    public whatIsA() { 
     return a 
    } 

    public func() { 
     return "${whatIsA()} + 5" 
    } 

    public test() { 
     return Eval.me(func()) 
    } 
} 
def a = new A() 
a.test() 
+0

使用Eval.me而不是eval/evaluate工作得很好,謝謝! – frmdstryr 2014-08-15 18:18:27

0

我不認爲這是有可能在目前的形式......我能拿出最好的將是要麼使用Eval.x像這樣:

public test() { 
    return Eval.x(this, '"${x.func()}"') 
} 

或在封閉包裝的表達(其那麼你可以改變的委託)

public test() { 
    def clos = Eval.me('{ -> func() }') 
    clos.delegate = this 
    clos.resolveStrategy = Closure.DELEGATE_ONLY 
    clos.call() 
} 

如果您希望這不是一個腳本運行,但作爲一個編譯的應用程序,也有可能是你可以帶着GroovyScriptEngine和/或GroovyShell路線。 (見:Evaluate Scripts with a Common Base Class

相關問題