Groovy traits in java classes

淺唱寂寞╮ 提交于 2020-02-06 00:49:11

问题


I am working on an existing java codebase but have convinced the team to use cross compilation so new development can be done in groovy, while still using the old codebase. Best of both worlds, low risk, lots of benefits, etc.

I have a problem i am trying to solve that is perfectly handled by Groovy's trait feature, but it has to work with the existing java classes or new ones for the dev's that still want to write in java.

doing class duck implements FlyingAbility { in java throws an error about implementation, and IntelliJ's automatix fix is to implement all of the methods in the trait in the java class, as if it was just an interface.

Is there a way to have traits use traits in java classes similarly to how they work in groovy classes?


回答1:


You can't use traits in Java classes. Groovy traits are implemented as a compile-time transformation of the class they're applied to, and Java classes don't pass through the Groovy compiler.

That said, it's usually very simple to convert Java code to Groovy, and adding @CompileStatic to the class typically generates code that performs about like the equivalent Java, although (for now) with a bit larger .class file.




回答2:


If you need to use just one trait you can create a proxy class in Groovy i.e.

GroovyTrait.groovy

trait GroovyTrait {
}

GroovyClass.groovy

class GroovyClass implements GroovyTrait {
}

JavaClass.java

class JavaClass extends GroovyClass {
}


来源:https://stackoverflow.com/questions/34912756/groovy-traits-in-java-classes

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