groovy - 如何创建类似 C# 的扩展方法
问题描述
我想将公共方法附加到类。这在 C# 中称为扩展方法。
package extensionMethods
class A {
def testA() {}
//def testB() {} Need to add a public method to this class A but we don't have access to the class
}
class B {
def test() {
def a = new A();
a.testA()
a.testB() //Need to add a public method to the Class A without defining the method in the class A
}
}
//In C# way -> Extension method
class C {
/* void testB(this A a) {
}*/
}
我们如何在 Groovy 中实现类似的方法?在上面的示例中,我想将方法附加testB()
到class A
解决方案
你会想要这样的东西:
package something
class SomeExtensionClass {
static void testB(A self) {
// ...
}
}
然后你的META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
扩展描述符......
moduleName=Test module for specifications
moduleVersion=1.0-test
extensionClasses=something.SomeExtensionClass
有关更多信息,请参阅http://groovy-lang.org/metaprogramming.html#_extension_modules。
推荐阅读
- javascript - 将更改的 HTML 保存到 Javascript 变量?
- actionscript-3 - AS3:如何检测负数
- python-3.x - 将 csv 列表导出为垂直(列)
- ruby - Ruby:在外部模块中调用时未定义 attr_accessor 方法
- swift - NSUserDefaultsController:“尝试将非属性列表对象...设置为键的 NSUserDefaults/CFPreferences 值...”
- matplotlib - 如何用不在当前数据框中的点绘制“最佳拟合线”?
- javascript - 如何在 html 中调用导航包装器上的 stickynavbar 函数?
- ionic-framework - 如何在我的 WordPress 网站的 ionic 应用程序中显示广告?
- git - 是否可以创建整个团队都可以使用的存储库的分支(而不是个人分支)?
- r - 找到属于另一个向量的一个因子的不同级别的向量的公共值