如果使用遗留库,如何避免Java中的未经检查的转换警告? [英] How to avoid unchecked-conversion-warning in Java, if you use legacy libraries?

查看:409
本文介绍了如果使用遗留库,如何避免Java中的未经检查的转换警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢java中的泛型特性并经常使用它。但是我有一个问题,如果我使用那些还没有意识到泛型的库。一个例子是servlet。如果使用 ServletRequest.getParameterMap(),结果将是一个原始映射,但它只包含 String 作为键, 字符串[] 作为值。所以我想把它分配给 Map< String,String []> 。但是对于这项任务,我得到了一个警告。我怎样才能避免这种警告与语言,而不是简单地通过 @SuppressWarnings 注释来压制警告。

解决方案

正如其他人所说,除了压制他们之外,警告是无法避免的。恕我直言,问题在于要么使用适用于小范围的注释来抛弃代码,要么在全局忽略它们并冒着错误。


$ b IIRC有一个建议,可以生成警告原始类型正在返回而不是在呼叫中。同时,我认为最好的方法是使用包装方法,以便将警告限制在一个地方,在这里可以忽略它们:

>

  class NoWarn {
public static Map< String,String []> getParameterMap(ServletRequest r)
{
@SuppressWarnings(unchecked)
Map< String,String []> result = r.getParameterMap();
返回结果;





$ b

注意
这个答案是用一个注释编辑的,注释不能在方法体内。这是不正确的,上面的语法正确。我已经回复了这个变化。

I like the generics-feature in java and use it often. But I have a problem, if I use libraries that aren't yet aware of generics. An example are servlets. If you use ServletRequest.getParameterMap() the result will be a raw map, but it includes only String as keys and String[] as values. So I want to assign it to a Map<String, String[]>. But for this assignment I get an warning. How can I avoid this warning with the language, not by simply suppressing the warning with the @SuppressWarnings annotation.

解决方案

As others have said the warnings cannot be avoided except by suppressing them. The issue IMHO is that either you have to litter your code with annotations that apply to small scope or ignore them globally and risk errors.

IIRC there is a proposal to generate warnings where the raw types are being returned instead of at the call.

Meanwhile, I think the best approach is to use a wrapper method so that the warnings are limited to a single place, where it is safe to ignore them:

class NoWarn {
  public static Map<String, String[]> getParameterMap(ServletRequest r) 
  {
    @SuppressWarnings("unchecked")
    Map<String, String[]> result = r.getParameterMap();
    return result;
  }
}

Note This answer was edited with a comment that annotations cannot be inside method bodies. That is incorrect, the above is syntactically correct. I have reverted the change.

这篇关于如果使用遗留库,如何避免Java中的未经检查的转换警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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