Solved

Unclear Java cast exception

Posted on 2013-02-05
6
629 Views
Last Modified: 2013-02-06
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
Comment
Question by:sae1962at
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
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
net.atos.roman.tmtbl.liaison.calendar.macros.CalendarMacrosDTO

Open in new window


Notice a difference?
0
 
LVL 1

Author Comment

by:sae1962at
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 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
 
LVL 35

Accepted Solution

by:
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) {
            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
Technology Partners: 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!

 
LVL 1

Author Comment

by:sae1962at
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.
TestGenerics.java
0
 
LVL 1

Author Closing Comment

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

Expert Comment

by:mccarl
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!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
Suggested Courses

751 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