Groovy closure not work with static final field from super class

走远了吗. 提交于 2019-12-10 18:17:21

问题


class Parent {
    final static String newLine = "*"
}
class Child extends Parent{
    List body = [3, 4, 5]
    String toString() {
        def str = new StringBuilder()
        body.each { str.append(it + newLine) }
        str
    }
}

def c = new Child()
println c

The above is one trivial sample to illustrate the problem. It couldn't be compiled using Groovy plugin on Eclipse. Remove either final or static in the field of super class solves the problem. However, I have no idea why it's the case.

http://groovy.codehaus.org/Groovy+Beans In this link it mentions the rules for property and fields used in Groovy. I suppose the one applied should be the last one, i.e. meta class. Unfortunately, I still couldn't understand the behavior.

The behavior is reproduced consistently in all versions of Groovy. Maybe someone could report one bug to Groovy team. I have never done this before. It would be more efficient if someone experienced could do that.


回答1:


This is most probably http://jira.codehaus.org/browse/GROOVY-5776 which is more difficult to fix than it looks like




回答2:


As blackdrag already pointed out: it's a bug. But another workaround is to add the protected keyword:

protected final static String newLine = "*"


来源:https://stackoverflow.com/questions/14552964/groovy-closure-not-work-with-static-final-field-from-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!