Unclear Java cast exception


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 net.atos.roman.tmtbl.liaison.calendar.macros.CalendarMacrosDTO

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

Thanks in advance!
Ahmet Ekrem SABANSenior IT consultantAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
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

käµfm³d 👽Commented:
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?
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
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 Macros.java 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.
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
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.
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
Found the weakness of Java type checking with generics quickly. Thank you!
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.