2016-01-22 28 views
1

我正在使用以下代码从Spring身份验证类中提取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<String,String>

+0

如果这可能,我会感到惊讶。 –

回答

2

你不能。

由于Authentication简单的getDetails()返回值定义为Object,你要投,虽然类型Map将在运行时进行检查,但仍然不能保证它映射(因为type erasureStringString

这意味着您在可能得到ClassCastException在稍后的点,当Map使用。这是警告试图告诉你的,你接受@SuppressWarnings的责任。

+0

感谢您的解释。那么使用它的正确方法是什么? – user1950349

+0

在你想要的地方添加@SuppressWarnings(“unchecked”)。如果将它添加到语句中,它不会意外隐藏在开发过程中稍后可能发生的另一个警告事件,如果将其添加到方法或类中,可能会发生这种情况。 – Andreas

0

通过执行铸造前检查的类型。

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

...你的问题可能是重复到: Type safety: Unchecked cast

相关问题