Bug 226662 - No error message for bad cast
Summary: No error message for bad cast
Status: CLOSED INVALID
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 3.4   Edit
Hardware: PC Windows XP
: P3 major (vote)
Target Milestone: 3.4 M7   Edit
Assignee: JDT-Core-Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2008-04-11 07:27 EDT by Gary Karasiuk CLA
Modified: 2008-04-14 12:16 EDT (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Gary Karasiuk CLA 2008-04-11 07:27:22 EDT
I am using Version: 3.4.0, Build id: I20080330-1350

I have the following method:

	public void test(Map<Integer, String> map){
		String key = null;
		map.get(key);
	}

I was very surprised to see that I didn't get any errors or warnings. How can the String "key" be cast to an Integer without that being an error?
Comment 1 Maxime Daniel CLA 2008-04-11 08:26:16 EDT
This is because, at least for the JDK 1.6 I use, Map<K, V>#get is defined as:
    V get(Object key);

(and not as V get(K key), where K would resolve to Integer in your case).

Hence no cast is needed at all. Please reopen if your definition of Map is different.
Comment 2 Gary Karasiuk CLA 2008-04-11 08:53:08 EDT
Thanks I had never noticed that.

I had just assumed it would be "V get(K key)" without ever actually looking. They must have had some sort of implementation reason for doing it as get(Object), but I don't think it is very intuitive. 

Comment 3 Maxime Daniel CLA 2008-04-11 09:27:32 EDT
You're welcome. I believe this comes from upward compatibility needs indeed (the API used get(Object) in the past, hence there must be many calls out there that rely on this - note also that implementors may throw an exception if they are not happy with the type they get, but are not required to do so).
Comment 4 Philipe Mulet CLA 2008-04-14 06:33:45 EDT
Yes, this is the idea. Same is true for list removals.
Comment 5 Gary Karasiuk CLA 2008-04-14 07:55:36 EDT
I did close this because I do agree that what is being done is "correct".

But just like it is correct to have an unused private method (and you can generate a warning for that), it would be nice to have a warning (that could be turned on or off) for this case.

I understand that the method signature needs to be this way for old code, but it is not what you would want or expect for new code. And over time you would want to fix up your old code as well.
Comment 6 Philipe Mulet CLA 2008-04-14 12:16:45 EDT
The compiler does not define the libraries you compile against; it simply consumes them. Diagnosing what you wanted would mean that somewhere there would be a library of suggested replacement signatures to use, with proper diagnosis.

I believe this is rather a job for a static analysis tool where it knows about code patterns etc...