使用expando调用groovy方法

时间:2016-06-20 02:11:35

标签: groovy

我不确定这是否可行,所以我有这个方法

callMeMethod(String param1)

我想调用类似

的方法
param1.callMeMethod()

但是当我尝试这样做时,我收到了一个错误

Unhandled Error: No signature of method: java.lang.String.callMeMethod() is applicable for argument types: () values: []

1 个答案:

答案 0 :(得分:0)

这是可能的,但您必须将它添加到param的metaClass(您提供的示例中的String)。 您可以通过以下方式完成此任务。

String.metaClass.callMeMethod = {-> println "function code can go here"}
String param1 = "meParam"
param1.callMeMethod()

output-> function code can go here

我也会看Category

traits作为可能更合适的替代方案