Unclear Java cast exception

Posted on 2013-02-05
Last Modified: 2013-02-06

I am currently a consultor in a Java Swing project that uses JGoodies 1.2.1. My current job is writing GUI dialogues. A few weeks ago, a colleague of us wrote a code generators that produce all dialogues that are not very complicated. So, for simple dialogues, we should use the generator.

When comparing the generated code with my own dialogue code, I get a class cast exception that I do not understand. Perhaps, you can help me.

The code uses so-called Data Transfer Objects (DTOs). I have a method in the generated code that is called loadObjects(), where I get the exception.

In the attached code, you see that for loop line exists two times, one being commented out. In this case, I get the eclipse (static syntactical) error "Type mismatch: Cannot convert from element type CalendarMacrosDTO to CalendarMacrosDTOAdapter". It is a clear error, so I comment the now uncommented line and introduce the commented line as code; there is no statical error now.

When I run the code, I get an exception at the now uncommented line for (final CalendarMacrosDTO dto : list) that reads

Exception in thread "main" java.lang.ClassCastException: net.atos.roman.tmtbl.client.gui.wizard.calendar.macros.model.CalendarMacrosDTOAdapter cannot be cast to

Obviously, I got the wires crossed. :-) Can you explain what I am doing wrong here?

Thanks in advance!
Question by:sae1962at
  • 3
  • 2
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38855054
Perhaps a bit of formatting will show you some clarity  : )

Exception in thread "main" java.lang.ClassCastException:

net.atos.roman.tmtbl.client.gui.wizard.calendar.macros.model.CalendarMacrosDTOAdapter            cannot be cast to

Open in new window

Notice a difference?

Author Comment

ID: 38855256
Thank you for the answer. I am aware that this cast does not work, but the problem is that the list should contain MacrosDTO. In reality, it contains MacrosDTOAdapters. What I do not understand is that what as.getObjectList() returns is accepted as a list of MacrosDTOs, but below, I suddenly cannot add the elements to a MacrosDTO variable in the for loop. If, however, I comment out the first for line and remove the comments of the second line (like it is seen in the attached file), I get an error from eclipse and cannot run it.

Let me reiterate my question: If somehow a list of MacrosDTOAdapters can be assigned to a List<MacrosDTO>, it should be possible to access each element as a MacrosDTO. If, on the other hand, the assignment is changed to List<MacrosDTOAdapter> list = as.getObjectList(); (that is what the debugger shows me to be the contents of the list returned by getObjectList()), I get an error of eclipse (statical error before running the code).

To me, a list of MacrosDTOAdapter should always be assignable to a list of MacrosDTOAdapter. If, however, it is possible to assign it to a list of MacrosDTOs, then it should be possible to "extract" each element of it as a MacrosDTO.
LVL 35

Accepted Solution

mccarl earned 400 total points
ID: 38857634
Ok, I *think* I know what is going on here. (Only *think* because I would need the code inside that getObjectList() method, and possibly other code, to fully confirm my thoughts).

What you need to remember is that with Generics, it is only a compile time concept. Once you have been able to successfully compile your code, that type information is 'erased' and now all your List's, etc can theoretically contain anything at all !

The below code is a small self contained example of what I think your problem is. Have a look over it, run it, you should also get a ClassCastException. Then I would probably go and have a look at that getObjectList() method and see if you can find the issue there.
import java.util.ArrayList;
import java.util.List;

public class TestGenerics {
    public static void main(String[] args) {
        List<Object1> object1List = getObject1List();
        for (Object1 object1 : object1List) {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static List<Object1> getObject1List() {
        List list = new ArrayList();
        list.add(new Object2());
        return list;

    private static class Object1 {
        public String toString() {
            return "Object1";
    private static class Object2 {
        public String toString() {
            return "Object2";

Open in new window

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.


Author Comment

ID: 38858668
You are very right, McCarl! I got the exception in your test code, modified it so that it does not give any runtime errors, looked to the code of getObjectsList() at the point you requested and solved the problem. This is a type-checking weakness of Java. :-)

I add the code for convenience that run without the error.

Author Closing Comment

ID: 38858670
Found the weakness of Java type checking with generics quickly. Thank you!
LVL 35

Expert Comment

ID: 38859326
Glad to help. :)

Just a point though... I wouldn't consider this a "weakness" of Java. Java never claims that Generics can be used to *ensure* runtime types are correct. However, I do concede that the language does heavily contribute to this common false assumption about what Generics are used for! Unfortunately, most teachings on the topic allow these false assumptions to continue by only showing how Generics are used and not trying to demonstrate what is actually going on somewhat under the hood. Hopefully, my little example above has given you a bit more knowledge on the more inner workings of Generics!

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
HSSFWorkbook cannot be resolved error 10 136
print map entry 34 75
ejb message driven bean mdb creation steps 2 34
Netbeans and org.apache.commons.lang3 issue 3 22
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question