在没有泛型的情况下使用遗留代码时如何避免Eclipse警告? [英] How to avoid Eclipse warnings when using legacy code without generics?

查看:388
本文介绍了在没有泛型的情况下使用遗留代码时如何避免Eclipse警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JSON.simple 从Java生成JSON输出。但是每次我调用jsonobj.put(this,that),我都会在Eclipse中看到一个警告:
$ b


类型安全性: put(Object,Object)方法属于原始类型HashMap。如果JSONObject是通用化的,那么干净的修复将是,但是因为它不是,所以我可以不要添加任何泛型类型参数来解决这个问题。我想关闭尽可能少的警告,因此在许多方法中添加@SuppressWarnings(unchecked)是没有吸引力的,但除了提出警告外,我还有其他选择吗?

解决方案

这里有一个选项。这有点难看,但允许你将被压制的警告范围限定在单独的操作中。



添加一个可以进行未经检查的强制转换的函数,并禁止其中的警告:

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

然后,您可以在没有编译器警告的情况下调用它:

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

通过这种方式,您可以确保不会抑制任何您实际希望看到的警告。


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.

这篇关于在没有泛型的情况下使用遗留代码时如何避免Eclipse警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆