简体   繁体   中英

How to avoid Eclipse warnings when using legacy code without generics?

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?

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.

您可以拥有每个项目的编译器设置,并且可以将这些警告更改为忽略

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM