3.4 M5 - Compiler error in cast [message #251516] |
Tue, 19 February 2008 06:58  |
Eclipse User |
|
|
|
Originally posted by: andre_andrade_costa.yahoo.com
I'm getting a cast error in Eclipse in the following lines:
----
Properties panels = new Properties();
panels.load(this.getClass().getResourceAsStream(FILE_PANEL)) ;
List<String> keys = new ArrayList<String>((Collection<? extends String>)
panels.keySet());
----
This does not happen in 3.3
|
|
|
|
|
Re: 3.4 M5 - Compiler error in cast [message #251575 is a reply to message #251516] |
Wed, 20 February 2008 15:22  |
Eclipse User |
|
|
|
Originally posted by: wharley.bea.com
"Andre" <andre_andrade_costa@yahoo.com> wrote in message
news:59790f6c2438d3133d3e25a2d83f32da$1@www.eclipse.org...
> I'm getting a cast error in Eclipse in the following lines:
> ----
> Properties panels = new Properties();
> panels.load(this.getClass().getResourceAsStream(FILE_PANEL)) ;
> List<String> keys = new ArrayList<String>((Collection<? extends String>)
> panels.keySet());
> ----
>
> This does not happen in 3.3
In Eclipse 3.3.2, I get a warning on the third line, "Type safety: Unchecked
cast from Set<Object> to Collection<? extends String>". In 3.4M5, as you
note, it's an error: "Cannot cast from Set<Object> to Collection<? extends
String>".
But enquiring minds might note that String is final, and wonder what happens
if we change the code to Collection<String>. Aha! Then, we get the same
"Cannot cast" error in both 3.3.2 and 3.4M5: "Cannot cast from Set<Object>
to Collection<String>"
So, it sounds like 3.3 allowed the cast to be treated just as a warning
rather than an error in this special "extends" case, and is changed in 3.4.
A bit more research reveals
https://bugs.eclipse.org/bugs/show_bug.cgi?id=89940 - it appears that what
happened was that the Java Language Spec was tightened up a bit around
wildcards.
If you really need this to work, you could just cast to a raw type, instead:
List<String> keys = new ArrayList<String>((Collection) panels.keySet());
That way you'll get an unsafe cast warning, appropriately, but not an error.
You can suppress the warning with @SuppressWarnings if you like.
***
Intuitively, "should it be an error"? It's clear that it's an unsafe cast -
there's nothing stopping someone from putting an Integer into the collection
along with the Strings, at any point. But that would just result in a
ClassCastException at runtime; so what? I'm not sure what the compiler's
guiding principle is on whether to consider a dubious cast a warning versus
an error.
|
|
|
Powered by
FUDForum. Page generated in 0.03930 seconds