Grails 检查instanceOf后的ClassCastException

Grails 检查instanceOf后的ClassCastException,grails,groovy,classcastexception,Grails,Groovy,Classcastexception,我有grails(版本3.2.11)应用程序(它包括groovy-2.4.11.jar)。 和下面的代码 @CompileStatic def removeAllErrors(DomainClass domainInstance) { newAssociationOperationRunnerBuilder(domainInstance) .setSkipChain({DomainObjectDetails<DomainObjectDataSingle> domai

我有grails(版本3.2.11)应用程序(它包括groovy-2.4.11.jar)。 和下面的代码

 @CompileStatic
def removeAllErrors(DomainClass domainInstance) {
    newAssociationOperationRunnerBuilder(domainInstance)
    .setSkipChain({DomainObjectDetails<DomainObjectDataSingle> domainObjectDetails ->
        skipValidation(domainObjectDetails.currentDomain.domainObject, domainObjectDetails.associationProp?.name)})
    .build().run({DomainObjectDetails<DomainObjectDataSingle> domainObjectDetails ->
        DomainClass domain = domainObjectDetails.currentDomain.domainObject
        if (domain instanceof GormValidateable) {
            ((GormValidateable)domain).clearErrors()
        }
        if(domain instanceof WarningsHolder) {
            WarningsHolder warningsHolder = domain as WarningsHolder //<--- line 120
            Warnings warnings = warningsHolder.getWarnings()
            warnings.clearWarnings(false, true)
        }
    })
}
你知道原因是什么吗? 请注意,我也有@CompileStatic

========================================================================= 此代码的早期版本没有@CompileStatic

 def removeAllErrors(def domainInstance) {
    newAssociationOperationRunnerBuilder(domainInstance)
    .setSkipChain({DomainObjectDetails<DomainObjectDataSingle> domainObjectDetails ->
        skipValidation(domainObjectDetails.currentDomain.domainObject, domainObjectDetails.associationProp?.name)})
    .build().run({DomainObjectDetails<DomainObjectDataSingle> domainObjectDetails ->
        domainObjectDetails.currentDomain.domainObject.clearErrors()
        if(domainObjectDetails.currentDomain.domainObject instanceof WarningsHolder) {
            Warnings warnings = domainObjectDetails.currentDomain.domainObject.getWarnings()
            warnings.clearWarnings(false, true)
        }
    })
}

您根本不应该将
instanceof
与代理一起使用,因为这将导致不可预测的结果

如果要检查类的对象,可以使用
isAssignableFrom()

isCase()
/
开关

switch( domain ){
  case GormValidateable: doStuff(); break
  case WarningsHolder: doOtherSTuff(); break
}

您根本不应该将
instanceof
与代理一起使用,因为这将导致不可预测的结果

如果要检查类的对象,可以使用
isAssignableFrom()

isCase()
/
开关

switch( domain ){
  case GormValidateable: doStuff(); break
  case WarningsHolder: doOtherSTuff(); break
}
if ( GormValidateable.isAssignableFrom( domain.getClass() ) ) {...}
switch( domain ){
  case GormValidateable: doStuff(); break
  case WarningsHolder: doOtherSTuff(); break
}