如何解决这个Java类型安全警告?

发布于 2024-09-03 10:53:44 字数 594 浏览 4 评论 0原文

Map session = ActionContext.getContext().getSession();
session.put("user", user);

此代码生成警告:类型安全:方法 put(Object, Object) 属于原始类型 Map。对泛型类型 Map的引用应该参数化

Map<String, Serializable> session = (Map<String, Serializable>)ActionContext.getContext().getSession();
session.put("user", user);

此代码生成警告:类型安全:未检查从 Map 到 Map的转换

getSession方法属于Struts2,所以我无法修改它。我想避免使用 @SuppressWarnings 因为其他警告可能有用。

我想世界上所有的 Struts2 用户都面临着同样的问题......有一个优雅的解决方案吗?

Map session = ActionContext.getContext().getSession();
session.put("user", user);

This code generates a warning: Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map<K,V> should be parameterized.

Map<String, Serializable> session = (Map<String, Serializable>)ActionContext.getContext().getSession();
session.put("user", user);

This code generates a warning: Type safety: Unchecked cast from Map to Map<String,Serializable>.

The getSession method belongs to Struts2 so I can't modify it. I would like to avoid using @SuppressWarnings because other warnings can be useful.

I guess all Struts2 users in the world faced the same problem... is there an elegant solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

那小子欠揍 2024-09-10 10:53:45

我认为除了 @SuppressWarnings("unchecked") 之外没有其他方法。我相信你可以把它放在有问题的线上方,它只会抑制该线。

编辑:您还可以执行 Map session = ActionContext.getContext().getSession(); 但我不确定你是否愿意这样做;您将无法以这种方式将任何内容放入映射中(因为编译器无法检查您所放入内容的类型),只能从中读取。

I don't think there's any other way but @SuppressWarnings("unchecked"). I believe you can put it just above the line in question, and it will only suppress that line.

Edit: you can also do Map<?, ?> session = ActionContext.getContext().getSession(); but I'm not sure how willing you are to do that; you won't be able to put anything into the map that way (since the compiler can't check the type of what you're putting), only read from it.

无敌元气妹 2024-09-10 10:53:45

处理这个问题最安全、最有效的方法可能是:

Map<?, ?> session = ActionContext.getContext().getSession();

然后对从会话映射中检索的对象进行类型转换。

@SuppressWarnings 方法实际上会生成相同的编译代码。然而,类型转换将是隐式的;即通过查看源代码不容易发现它。 @SuppressWarnings 注释可以(假设)抑制同一代码块中代表真实错误的一些其他警告;即会导致隐藏类型转换等之一在运行时失败。

其他更昂贵的替代方案包括:

  • Map 逐项复制到新的 Map 实例来转换键和值分别为 StringSerialized,或者

  • 如下所示的通用方法安全地执行类型转换。


@SuppressWarnings("unchecked")
public <K,V> Map<K,V> castMap(Map<?, ?> map, Class<K> kClass, Class<V> vClass) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        kClass.cast(entry.getKey());
        vClass.cast(entry.getValue());
    }
    return (Map<K,V>) map;
}

The safest, most efficient way to deal with this is probably:

Map<?, ?> session = ActionContext.getContext().getSession();

and then type cast the objects retrieved from the session map.

The @SuppressWarnings approach will actually result in compiled code that is identical. However the type cast will be implicit; i.e. it won't be easy to spot by looking at the source code. And the @SuppressWarnings annotation could (hypothetically) suppress some other warning in the same code block that represents a real error; i.e. one that will result in one of the hidden typecasts, etc failing at runtime.

Other more expensive alternatives include:

  • an entry by entry copy from the Map<?, ?> to a new Map<String, Serializable> instance casting the keys and values to String and Serializable respectively, or

  • a generic method like the following that performs the typecast safely.


@SuppressWarnings("unchecked")
public <K,V> Map<K,V> castMap(Map<?, ?> map, Class<K> kClass, Class<V> vClass) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        kClass.cast(entry.getKey());
        vClass.cast(entry.getValue());
    }
    return (Map<K,V>) map;
}
千笙结 2024-09-10 10:53:45

您使用的是哪个版本的 Struts 2(尤其是 XWork)?对我来说,您的以下代码给出了一个错误:

Map<String, Serializable> session = (Map<String, Serializable>)ActionContext.getContext().getSession();
session.put("user", user);

Cannot cast from Map<String,Object> to Map<String,Serializable>.

另一方面,这可以工作并且不会给出任何警告:

Map<String, Object> session = ActionContext.getContext().getSession();

What version of Struts 2 (especially XWork) are you using? For me, your following code gives an error:

Map<String, Serializable> session = (Map<String, Serializable>)ActionContext.getContext().getSession();
session.put("user", user);

Cannot cast from Map<String,Object> to Map<String,Serializable>.

This, on the other hand, works and gives no warnings:

Map<String, Object> session = ActionContext.getContext().getSession();
土豪我们做朋友吧 2024-09-10 10:53:45

它要求您参数化该值,如果该值需要参数则传递它们。

例如,

Map<Integer, Map> vCombinedCodeMap = new HashMap<>();

将对“参数化”Map 发出警告。

所以正确的格式如下:

Map<Integer, Map<String, String>> vCombinedCodeMap = new HashMap<>();

It is requesting you to parameterize the value, if the value needs parameters then pass them.

For example

Map<Integer, Map> vCombinedCodeMap = new HashMap<>();

will give warning for "parameterized" Map<Integer, Map>.

so the correct format is the following:

Map<Integer, Map<String, String>> vCombinedCodeMap = new HashMap<>();
江挽川 2024-09-10 10:53:45

如果你这样做怎么办:

Map<String, Serializable> session = ActionContext.getContext().getSession();

What if you do it like this:

Map<String, Serializable> session = ActionContext.getContext().getSession();
信仰 2024-09-10 10:53:45

扮演以下角色,

public void setSession(Map<String, Object> sessionMap) {

    // TODO Auto-generated method stub

    this.sessionMap = (SessionMap<String, Object>) sessionMap;
}

Cast as Following,

public void setSession(Map<String, Object> sessionMap) {

    // TODO Auto-generated method stub

    this.sessionMap = (SessionMap<String, Object>) sessionMap;
}
可爱咩 2024-09-10 10:53:45

只需在 @GET 方法顶部写入 @SuppressWarnings("unchecked") 即可,希望对您有所帮助。

just write @SuppressWarnings("unchecked") at top of the @GET method, hope it will help you.

瞳孔里扚悲伤 2024-09-10 10:53:45
@SuppressWarnings("unchecked")
public class CustomHashMap<K, V> {

  private class Entry {
    private K key;
    private V value;

    public Entry(K key, V value) {
      this.key = key;
      this.value = value;
    }

  }

  private LinkedList<Entry>[] entries = new LinkedList[5]; // this line shows warning to check types
}
@SuppressWarnings("unchecked")
public class CustomHashMap<K, V> {

  private class Entry {
    private K key;
    private V value;

    public Entry(K key, V value) {
      this.key = key;
      this.value = value;
    }

  }

  private LinkedList<Entry>[] entries = new LinkedList[5]; // this line shows warning to check types
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文