2015-10-17 55 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分钟:-)很高兴它的排序虽然 –