views:

143

answers:

3

I'm using JSON.simple to generate JSON output from Java. But every time I call jsonobj.put("this", "that"), I see a warning in Eclipse:

Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized

The clean fix would be if JSONObject were genericized, but since it isn't, I can't add any generic type parameters to fix this. I'd like to switch off as few warnings as possible, so adding "@SuppressWarnings("unchecked")" to lots of methods is unappealing, but do I have any other option besides putting up with the warnings?

+5  A: 

you can have a per project compiler settings and you can change those warnings to ignore.

Omry
That's even more extreme than adding @SuppressWarnings("unchecked") to the relevant methods; my issue is that I'd like to see as many warnings as possible while suppressing this one.
Paul Crowley
you can suppress this specific warning in your legacy project configuration. nothing extreme about it.
Omry
@Omry: it's extreme because *his* project isn't legacy, just the library he is referencing. Your suggestion is for his entire project to suppress warnings.
Kip
I don't think you get such warnings for code you don't compile. but if you need compile that code as part of your project you will indeed have to use more specific methods. however, I suggest that you just create a jar out of that library instead of compiling as a part of your project.
Omry
Omry: I'm not compiling the code for JSONObject as part of my code, I'm including it through Maven. The warning is in my code, which is not legacy code. Kip's comment is correct. The accepted solution addresses my situation exactly - make sure you see how it does that before comparing it to your solution.
Paul Crowley
+4  A: 

Write some helper methods, or wrapper classes for the library. Add the @SuppressWarnings("unchecked") only to those helpers. Then use the helpers to perform the interaction with the library.

Chris Lercher
This looks to be the best solution so far, thanks. Eclipse is just wrong to be warning me about this, isn't it? These errors should be in the JSONObject code, not my code.
Paul Crowley
@Paul: Eclipse is right, because that's the way it's specified for Java. You get the warning, because you're using a raw method from HashMap (you're forced to do that, because JSONObject extends HashMap).
Chris Lercher
+2  A: 

Here's one option. It's a bit ugly, but allows you to scope the the suppressed warning to only that individual operation.

Add a function which does the unchecked cast, and suppress warnings on it:

@SuppressWarnings("unchecked")
private final static Map<Object,Object> asMap(JSONObject j)
{
  return j;
}

Then you can call it without compiler warnings:

asMap(jsonobj).put("this", "that");

This way, you can be sure that you aren't suppressing any warnings that you actually want to see.

Kip