【问题标题】:Why am I getting this ClassCastException during an assignment where the two types are the same? (Groovy / Hibernate)为什么我在两种类型相同的分配期间收到此 ClassCastException? (常规/休眠)
【发布时间】:2022-07-01 01:00:25
【问题描述】:

我定义了以下类:

enum FruitTypeEnum {
    APPLE,
    BANANA,
    NONE
}

// POGO
class FruitDTO {
    FruitTypeEnum fruitType
}

// Hibernate Entity
abstract class Farm {
    FruitTypeEnum fruitType
}

private getFruitDTO(Farm farm) {
    def fruitDTO = new FruitDTO()
    fruitDTO.fruitType = farm.fruitType
    fruitDTO
}

当我尝试执行getFruitDTO 函数时,分配fruitDTO.fruitType = farm.fruitType 有50% 的时间会引发以下异常:

java.lang.IllegalArgumentException: java.lang.ClassCastException@564a5444
 at FarmController.getFruitDTO(FarmController.groovy:126)

我已附加调试器并验证分配的左侧和右侧都是相同的数据类型。那么我如何获得ClassCastException

【问题讨论】:

    标签: hibernate grails groovy classcastexception


    【解决方案1】:

    因为farm参数是一个Hibernate实体,它可能是一个HibernateProxy实例。您可能会认为,当您尝试访问 type 字段时,您会得到一个明确的异常,但由于某种原因,在这种情况下,您会得到我在上面发布的 ClassCastException。如果您运行调试器并查看代码,您会发现赋值的两边确实是完全相同的类,但如果确实是代理对象,farm 实例的类型将是 Farm$HibernateProxy$...

    只需unwrap the proxy,您将避免此错误:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2017-11-23
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2010-10-15
      相关资源
      最近更新 更多