Reputation:
The following statement causes a warning in Eclipse:
Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
Warning:
Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,String>
What is the best practice to handle this warning? Should I add an SupressWarning("unchecked") annotation? For the whole class? Or just the method? Or should I just ignore the warning? Or how can I get rid of this warning?
Upvotes: 2
Views: 3135
Reputation: 691913
If the method returns a raw map, the only thing you can do is to make sure (from the doc or from the code) that the Map is indeed a Map<String, String>
, and ignore the warning. The compiler doesn't have any way to check that the returned Map is ideed a Map<String, String>
.
You should ignore the warning at the smallest possible scope, else other unsafe code could be added without warning from the compiler.
Upvotes: 1
Reputation: 15729
I find these warnings on the declaration line highly annoying. And meaningless, since, deep down inside, I know that there is type erasure and it the compiler is complaining about nothing. So I ignore them. However, this may not be a best practice and I'm quite interested in how others approach them. Java 7 made some improvements, IIRC, you can now go
List<String> = new ArrayList<>();
and save some redundant typing of "String" and avoid the warning.
Note - I do pay attention to warnings that are not on the declaration line.
Upvotes: 1
Reputation: 47994
The only way to 'get rid' of it permanently is to upgrade to a Java 5 or later-only version of your API that returns a parameterized map.
The simplest thing to do to sort of 'clean it up' is wrap the method that returns a RAW type in a class of your own, perform the cast there, and suppress the unchecked warning. This way at least it's done in a single place and you're not using @SuppressWarnings
all over the place where it may accidentally also hide a "genuine" warning.
Upvotes: 2
Reputation: 143264
Until DefaultCodeFormatterConstants.getEclipseDefaultSettings
is properly generified, I'd consider making a generified wrapper for it, and having the annotation on the internal local variable declaration inside of it. Also include a comment explaining why the annotation is "safe".
In general, you want the scope of a SuppressWarnings
annotation to be as small as possible, and you want to have as few of them as possible. You should also have a comment explaining your reasoning each time you use one.
Upvotes: 9