views:

225

answers:

6

Hi,

I have traced an issue with an application I am developing, it is giving me a type cast exception. Funny thing is it is saying it cannot cast "entities.Movie cannot be cast to entities.Movie"?! movies is an ArrayList.

    try {
        movies = getMovies();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        try {
            for (Movie movie : movies) {
                output.append("                 <tr>\n");
                output.append("                     <td>" + movie.getId() + "</td>");
                output.append("                 </tr>\n");
            }
         } catch (Exception e) {
             e.printStackTrace(System.out);
         }
     }
+7  A: 

Sounds like a classloader conflict. The same class definition, loaded by different classloaders, is seen as two distinct classes by the JVM.

With this little info, there is not much more to say. See this article for details on classloaders and their problems.

See also this earlier answer of mine to a similar problem.

Péter Török
+4  A: 

Possibly a class loader issue (if your application has more than one)

In a debugger, have a look at the Class objects from the getClass() call for a member of movies, and compare it to that for a locally constructed Movie object.

If they are different this may then allow you to trace what's happening. The class object will allow you to see which class loader has loaded the definition.

If you have two different class definitions loaded, you need to track down where your JAR file is being loaded twice.

John Smith
A: 

In addition to the classloader issue, I suspect that you are also doing some unsafe type conversions somewhere involving a Collection<Movie> instance or similar.

Stephen C
A: 

Check that both classes were compiled with the same version of Java.

maclema
Classes can be compiled with different versions without causing a `ClassCastException`. You will get an `UnsupportedClassVersionError` if you compile though with a more recent version and attempt to run on an earlier JVM.
Kevin Brock
Ah yes, That is correct.
maclema
A: 

i also suspect a classloader issue, but you could also check that your not having a serialversionuid problem.

Nico
A: 

Another possibility, if you have any code generation (e.g. from an ORM) going on is that the IDE is out of step with the files on disk, in which case refreshing the IDE project and doing a clean build may help.

If not, do you actually have two classes with the same name in different packages? If so it may be a case of trying to cast from one to the other as you have imported the "wrong" one.

pdbartlett