相关疑难解决方法(0)

如何处理未经检查的投射警告?

Eclipse正在向我发出以下形式的警告:

类型安全:从Object到HashMap的未选中转换

这是来自对我无法控制的API的调用返回Object:

HashMap<String, String> getItems(javax.servlet.http.HttpSession session) {
  HashMap<String, String> theHash = (HashMap<String, String>)session.getAttribute("attributeKey");
  return theHash;
}
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我想避免Eclipse警告,因为理论上它们至少表明存在潜在的代码问题.但是,我还没有找到一种消除这种方法的好方法.我可以将涉及的单行提取到方法中并添加@SuppressWarnings("unchecked")到该方法,从而限制了我忽略警告的代码块的影响.有更好的选择吗?我不想在Eclipse中关闭这些警告.

在我来到代码之前,它更简单,但仍然引发了警告:

HashMap getItems(javax.servlet.http.HttpSession session) {
  HashMap theHash = (HashMap)session.getAttribute("attributeKey");
  return theHash;
}
Run Code Online (Sandbox Code Playgroud)

当您尝试使用哈希时,问题出在其他地方,您会收到警告:

HashMap items = getItems(session);
items.put("this", "that");

Type safety: The method put(Object, Object) belongs to the raw type HashMap.  References to generic type HashMap<K,V> should be parameterized.
Run Code Online (Sandbox Code Playgroud)

java generics warnings

583
推荐指数
12
解决办法
42万
查看次数

标签 统计

generics ×1

java ×1

warnings ×1