2015-10-17 41 views
2

使用Groovy .& operator可以創建靜態方法的引用,如通PARAM用。&運算符靜態方法

def static xyz(name='Joe') { 
println "Hello ${name}" 
} 

// NOTE: ConsoleScript number part varies 
def ref = ConsoleScript52.&xyz 

而且可以easilly稱爲無參數,可以作爲

ref() // prints "Hello " 

但這個方法如何用params調用? ref('John')給出了一個錯誤groovy.lang.MissingMethodException: No signature of method: ConsoleScript52.xyz() is applicable for argument types: (java.lang.String) values: [John]

請注意,當使用ref調用靜態方法時,Groovy甚至不會在上面的示例中使用名稱參數的默認值。

回答

1

您可能正在使用一個ConsoleScript實例,你沒有定義與參數方法。

在下面的代碼,在我的控制檯(ConsoleScript8)的執行Y規定的方法hello()不帶參數(添加「腳本號」,清楚):

println this.getClass().getName() 
println '' 

def static hello() { 
    println "(8) Hello" 
} 

def h8 = ConsoleScript8.&hello 
h8() 
h8('Joe') 

而且它產生在未來執行以下操作:

ConsoleScript9 

(8) Hello 
Exception thrown 

groovy.lang.MissingMethodException: No signature of method: ConsoleScript9.hello() is applicable for argument types: (java.lang.String) values: [Joe] 

,並在前ecution(ConsoleScript10)我修改它添加默認的參數:

println this.getClass().getName() 
println '' 

def static hello(name='amigo') { 
    println "(10) Hello ${name}" 
} 

def h10 = ConsoleScript10.&hello 
h10() 
h10('Joe') 

println '--' 

def h8 = ConsoleScript8.&hello 
h8() 
h8('Joe') 

而且它產生:

ConsoleScript12 

(10) Hello amigo 
(10) Hello Joe 
-- 
(8) Hello 
Exception thrown 

groovy.lang.MissingMethodException: No signature of method: ConsoleScript8.hello() is applicable for argument types: (java.lang.String) values: [Joe] 

,如果你使用一個明確的類更容易:

class Greeter { 
    def static hello(name='Joe') { 
     "Hello ${name}" 
    } 
} 

def hi = Greeter.&hello 
assert hi() == 'Hello Joe' 
assert hi('Tom') == 'Hello Tom' 
+0

你是對的,問題是通過使用顯式類來解決的。 – kaskelotti

1

什麼版本的Groovy?這適用於Groovy的2.4.5:

class Test { 
    static greet(name = 'tim') { 
     "Hello ${name.capitalize()}" 
    } 
} 

// regular static calls 
assert Test.greet()    == 'Hello Tim' 
assert Test.greet('kaskelotti') == 'Hello Kaskelotti' 

// Create a reference to the static method 
def ref = Test.&greet 

// Calling the reference works as well 
assert ref()    == 'Hello Tim' 
assert ref('kaskelotti') == 'Hello Kaskelotti' 
+0

對不起蒂姆,你正如上面的@jalopaba一樣正確,但速度稍慢:)。當您的示例中直接定義靜態方法而不是將其作爲類的一部分時,會出現問題。 – kaskelotti

+0

而groovy控制檯聲明它的版本是2.4.5 – kaskelotti

+0

@kaskelotti我實際上更快了大約2分鐘:-)很高興它的排序雖然 –