简体   繁体   English

引用Java超类的属性时使用groovy'super'关键字

[英]Using groovy 'super' keyword when referencing properties of a java superclass

I've inherited a large groovy/java project and I am stumbling upon a usage pattern that just doesn't seem to work, but I can't figure out why. 我继承了一个大型的groovy / java项目,并且绊倒了一个似乎无法使用的使用模式,但我不知道为什么。

My predecessor makes frequent use of a java superclass and many groovy subclasses. 我的前任经常使用Java超类和许多groovy子类。 In the subclasses, he has getters that perform a lazy initialize and then, through the use of a property, set a value on the super class. 在子类中,他具有执行延迟初始化的吸气剂,然后通过使用属性在超类上设置值。 Unfortunately, this seems to throw a NoSuchFieldError. 不幸的是,这似乎引发了NoSuchFieldError。

I was able to reproduce this in a small test case, given below. 我能够在下面给出的一个小测试用例中重现它。 Essentially, referencing a property as "super.property" is throwing a NoSuchFieldError, but referencing it as just "property" works fine. 本质上,将属性引用为“ super.property”会引发NoSuchFieldError,但仅将其引用为“ property”就可以正常工作。

Here's some Java base classes: 这是一些Java基类:

public interface Content {
     public String getValue();
}

public class HolderJava {
     private Content _content;
     public Content getContent() { return _content; }
     public void setContent(Content value) { _content = value; }
}

And here are some groovy classes that extend them: 以下是一些扩展它们的常规类:

class ContentGroovy implements Content {
     def     value
     public String getValue() {
         value
     }
}

class HolderGroovy extends HolderJava {
     public ContentGroovy getContent() {
         ContentGroovy    newContent = new ContentGroovy()
         newContent.value = "snarf"

         // doesn't work, throws NoSuchFieldError
         //super.content = newContent

         // works
         content = newContent

         newContent
     }

     public static void main( String[] args ) {
         println( new HolderGroovy().getContent().getValue() )
     }
}

seemed to work fine when I pasted the code into GroovyConsole. 当我将代码粘贴到GroovyConsole中时,似乎工作正常。 Is the Java pre-compiled or compiled with groovyc? Java是使用groovyc预编译还是编译的?

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

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