groovy - 在私有方法上使用闭包子类化一个类
问题描述
我有一个 Groovy 类,它恰好有调用私有方法的闭包。它工作得很好,直到我尝试创建它的子类,导致MissingMethodException
.
示例代码:
class SomeClass {
void doStuff() {
println(['a', 'b'].collect { toUpper(it) })
}
private String toUpper(String x) {
return x.toUpperCase()
}
}
class Wat {
static void main(String[] args) {
def x = new SomeClass() {}
x.doStuff()
}
}
...崩溃:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static com.example.Wat.toUpper() is applicable for argument types: (String) values: [a]
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1573)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1559)
...
难道我做错了什么?除了保护所有方法之外,是否有一个明智的出路?
解决方案
我无法提供更好的解决方案,只能使用中间函数:
class SomeClass {
void doStuff() {
println(['a', 'b'].collect { pass(it) })
}
def pass(x) { toUpper(x) }
private String toUpper(String x) {
x.toUpperCase()
}
}
def x = new SomeClass() {}
x.doStuff()
推荐阅读
- python - Julia DataFrames 上的条件选择
- java - 启动应用程序时它崩溃并关闭应用程序
- audio - 如何在archlinux中为每个应用程序选择不同的音频输出
- reactjs - 在 react native 中输入我的 inputText 时如何设置进度条值?
- r - 看似不正确的答案来自 R 中的马赛克Calc::antiD
- pandas - Pandas 从 Dataframe 创建 dict
- javascript - 如果我在 if-else 阶梯中的 if 语句之后没有返回任何内容;默认返回值是多少?
- r - 在 R 中重建数据框的内容
- c# - 我正在将 C# 应用程序从 oracle 11 迁移到 oracle 19,并且正在发生此错误堆栈:
- powershell - 多台服务器上的 SMBShare 权限