Solved

Unclear Java cast exception

Posted on 2013-02-05
6
612 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
  • 3
  • 2
6 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Author Comment

by:sae1962at
Comment Utility
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
Comment Utility
Found the weakness of Java type checking with generics quickly. Thank you!
0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

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 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…
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.

743 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now