简体   繁体   English

Groovy 子类称为访问闭包的超类方法

[英]Groovy subclass called superclass method that accesses closure

I have a groovy superclass that looks like:我有一个看起来像的 groovy 超类:

class AGroovyClass {
   private String str = "hello"
   void printString(int nTimes) {
     nTimes.times { println str } 
  }        
}

and subclass和子类

class AGroovySubclass extends AGroovyClass {
   // some other subclass methods
}

My client code calls:我的客户端代码调用:

new AGroovySubclass().printString(5)

And this actually breaks because it says that that there is no such property "str" for AGroovySubclass这实际上中断了,因为它说 AgroovySubclass 没有这样的属性“str”

I would have thought since the printString method is in AGroovyClass, it should have no problem accessing the "str" property, but clearly I am incorrect.我原以为因为printString 方法在AGroovyClass 中,所以访问“str”属性应该没有问题,但显然我是不正确的。 If I wanted to keep "str" private, what is the appropriate way to make this work?如果我想保持“str”私有,那么使这项工作的适当方法是什么?

It is an old bug with private access modifier.这是一个带有私有访问修饰符的旧错误。 It works if you define str protected.如果您定义 str protected ,它会起作用。 https://issues.apache.org/jira/browse/GROOVY-2433 https://issues.apache.org/jira/browse/GROOVY-2433

edit: Can you avoid closure, use a for loop instead?编辑:你能避免关闭,而是使用 for 循环吗? Not so cool, but works :)不是很酷,但有效:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM