我有一个mixin类,它为不共享共同遗产的不同类型的功能捆绑在一起。混合是使用@Mixin注释应用的,因此它在编译时处理。Groovy中'return this'的类型@Mixin
作为方法调用的结果,一些mixin方法返回这个。问题是这个是混合类型,而不是基类的类型。当我想要在应用程序的其余部分中键入工作时抛出一个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
}
此解决方案有效,谢谢。由于我的Mixin必须被初始化,所以我选择用这个方法调用这个方法init(this),所以我可以通过这种方式将“真实的”这个传递给Mixin - 对我来说似乎更加清洁。但是,两种解决方法都有不对的地方,它们不应该是必需的。 – Ice09
这种方法解决了我的问题,但是Ice09已经说过这种解决方法并不合适。 – Ruben