Why am I getting this ClassCastException during an assignment where the two types are the same? (Groovy / Hibernate)

Viewed 25

I have the following classes defined:

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
}

When I attempt to execute the getFruitDTO function, 50% of the time the assignment fruitDTO.fruitType = farm.fruitType throws the following exception:

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

I have attached the debugger and verified that the left hand side and the right hand side of the assignment are both the same datatype. So how am I getting a ClassCastException?

1 Answers

Because the farm parameter is a Hibernate entity, it may be a HibernateProxy instance. You would think that one would get an explicit exception stating that when you attempt to access the type field, but for some reason in this case you get the ClassCastException I posted above. If you run the debugger and take a look at the code you will see that both sides of the assignment are indeed the exact same class, but the farm instance will be of type Farm$HibernateProxy$... if indeed it is a proxy object.

Just unwrap the proxy and you will avoid this error :-)

Related