Groovy子类称为超类方法访问闭包 [英] Groovy subclass called superclass method that accesses closure

查看:261
本文介绍了Groovy子类称为超类方法访问闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个groovy超类,看起来像:

I have a groovy superclass that looks like:

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

和子类

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

我的客户端代码调用:

new AGroovySubclass().printString(5)

这实际上打破了,因为它说,没有这样的属性str为AGroovySubclass

And this actually breaks because it says that that there is no such property "str" for AGroovySubclass

我会想,因为printString方法是在AGroovyClass,应该没有问题访问str属性,但显然我不正确。如果我想保持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. If I wanted to keep "str" private, what is the appropriate way to make this work?

推荐答案

与私人访问修饰符。它工作如果你定义str保护。
http://jira.codehaus.org/browse/GROOVY-2433

It is an old bug with private access modifier. It works if you define str protected. http://jira.codehaus.org/browse/GROOVY-2433

编辑:你能避免关闭,使用for循环吗?不太酷,但工作原理:)

edit: Can you avoid closure, use a for loop instead? Not so cool, but works :)

这篇关于Groovy子类称为超类方法访问闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆