Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 639
  • Last Modified:

Unclear Java cast exception

Hello!

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!
Macros.java
loadObject-error.PNG
0
Ahmet Ekrem SABAN
Asked:
Ahmet Ekrem SABAN
  • 3
  • 2
1 Solution
 
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
net.atos.roman.tmtbl.liaison.calendar.macros.CalendarMacrosDTO

Open in new window


Notice a difference?
0
 
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.
0
 
mccarlIT 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) {
            System.out.println(object1);
        }
    }
    
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static List<Object1> getObject1List() {
        List list = new ArrayList();
        list.add(new Object2());
        return list;
    }



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

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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.
TestGenerics.java
0
 
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
Found the weakness of Java type checking with generics quickly. Thank you!
0
 
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!
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now