karoma
karoma

Reputation: 1558

ClassCastException from exact same class

I'm running a database query and trying to cast the result to a Customer object, but I'm getting an error saying:

java.lang.ClassCastException: Entities.Customer cannot be cast to Entities.Customer

My code:

Customer c = (Customer)em.createNamedQuery("Customer.findByEmail")
        .setParameter("email", user)
        .getSingleResult();

I've read that this is due to classloaders, but to be honest it's a bit over my head. Is there a huge issue somewhere else, or am I just casting it incorrectly?

Upvotes: 0

Views: 2759

Answers (3)

Kayaman
Kayaman

Reputation: 73528

It looks like you have 2 ClassLoaders involved. You can check the classloaders with

Customer.class.getClassLoader();

em.createNamedQuery("Customer.findByEmail").setParameter("email", user).getSingleResult().getClass().getClassLoader();

Then you can try to find more information.

Upvotes: 3

Arnaud Potier
Arnaud Potier

Reputation: 1780

Like allprog said it is because the class that is being given back to you comes from a different jar than the one of your webapp (I'm assuming you are working on a webapp).

At runtime, your Customer loaded by the class loader from one jar (or your app) is cast into the customer from an other jar (or app).

So different possibilities:

  1. either the version of "Customer" are different and the classLoader the same
  2. or the two Customers are the same and the classloaders different.

In both cases you get the same error.

you can try to decompile your classes using javap to see what happens.

If you want to know more about classLoading: http://zeroturnaround.com/rebellabs/video-do-you-really-get-class-loaders-a-jazoon-talk-by-jevgeni-kabanov/

Upvotes: 0

Neeraj Krishna
Neeraj Krishna

Reputation: 1615

If you have a choice, I would suggest using JPA 2.0 and use:

<T> TypedQuery<T> createNamedQuery(java.lang.String name,
                               java.lang.Class<T> resultClass)

I think it should avoid class cast exception.

Upvotes: 0

Related Questions