【问题标题】:How to get rid of "Type safety: Unchecked cast from Object to Map<String,String>"如何摆脱“类型安全:从 Object 到 Map<String,String> 的未经检查的强制转换”
【发布时间】:2016-01-22 22:31:09
【问题描述】:

我正在使用下面的代码从 Spring Authentication 类中提取 deviceId

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.google.common.base.Optional;

public static Optional<String> getId() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.isAuthenticated()) {
        return Optional.absent();
    }
    // I see a warning as "Type safety: Unchecked cast from Object to Map<String,String>"
    Map<String, String> details = (Map<String, String>) auth.getDetails();
    return Optional.of(details.get("deviceId"));
}

我如何摆脱这种类型安全警告消息?我想避免添加Suprress Warnings 标签。

类型安全:未经检查的从Object 转换为Map&lt;String,String&gt;

【问题讨论】:

  • 如果这是可能的,我会感到惊讶。

标签: java dictionary spring-security


【解决方案1】:

你不能。

由于Authentication 只是将getDetails() 的返回值定义为Object,因此您必须进行强制转换,虽然Map 类型会在运行时检查,但仍然不能保证它映射StringString(因为type erasure)。

这意味着您可能在稍后使用Map 时获得ClassCastException。这就是警告试图告诉您的内容,您可以通过添加 @SuppressWarnings 来承担责任。

【讨论】:

  • 感谢您的解释。那么正确的使用方法是什么?
  • 在你想要的地方添加@SuppressWarnings("unchecked")。如果将它添加到语句中,它不会意外隐藏在开发过程中稍后可能出现的警告的另一种情况,如果添加到方法或类中可能会出现这种情况。
【解决方案2】:

通过在执行强制转换之前检查类型。

if(auth.getDetails() instanceof Map){
   //here your cast
}

...您的问题可能与以下内容重复: Type safety: Unchecked cast

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2022-02-03
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多