我有一个 mixin 类,它捆绑了不具有共同遗产的不同类型的功能。混合是使用@Mixin注释应用的,因此它是在编译时处理的。
一些 mixin 方法返回 this 作为方法调用的结果。问题是 this 是混合类型,而不是基类的类型。当我想在应用程序的其余部分中键入时,会抛出 ClassCastException ,表示混合类型无法转换为基本类型。
在下面的示例代码中,return this
返回 AMixin 类型的对象,而不是 BaseClass 类型的对象。
如何让 return this
返回 BaseClass 类型的对象而不是 AMixin 类型的对象?
class AMixin {
def getWhatIWant(){
if(isWhatIwant){
return this
} else {
getChildWhatIWant()
}
}
def getChildWhatIWant(){
for (def child in childred) {
def whatIWant = child.getWhatIWant()
if (whatIWant) {
return whatIWant
}
}
return null
}
}
@Mixin(AMixin)
class BaseClass {
boolean isWhatiWant
List<baseClass> children
}
最佳答案
我刚刚遇到了同样的情况。我通过将具体类中的“this”设置为具体类中的私有(private)变量“me”并在 Mixin 类中返回“me”来解决这个问题。例如:
class MyMixin {
def mixinMethod() {
// do stuff
return me
}
}
@Mixin(MyMixin)
class MyConcreteClass {
private MyConcreteClass me
MyConcreteClass() {
me = this
}
}
我觉得这有点笨拙,但我认为它比其他解决方案简单得多。我个人需要能够在多个类中使用相同的 Mixin,如果您无法将多个类别分配给单个 Mixin 类,那么听起来其他建议的解决方案将不允许这样做。
关于groovy - Groovy @Mixin 中 'return this' 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230889/