简体   繁体   中英

Groovy closure not work with static final field from super class

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, ie 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.

这很可能是https://issues.apache.org/jira/browse/GROOVY-5776 ,它比看起来更难修复

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

protected final static String newLine = "*"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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