Java 如何摆脱;类型安全:未选中从对象到贴图的强制转换<;字符串,字符串>&引用;
我使用下面的代码从Spring身份验证类中提取Java 如何摆脱;类型安全:未选中从对象到贴图的强制转换<;字符串,字符串>&引用;,java,dictionary,spring-security,Java,Dictionary,Spring Security,我使用下面的代码从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() {
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"));
}
导入org.springframework.security.core.Authentication;
导入org.springframework.security.core.context.SecurityContextHolder;
导入com.google.common.base.Optional;
公共静态可选getId(){
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
如果(!auth.isAuthenticated()){
返回可选的。缺席();
}
//我看到一条警告:“类型安全:未选中从对象到映射的强制转换”
Map details=(Map)auth.getDetails();
返回可选的.of(details.get(“deviceId”));
}
我如何克服这种类型的安全警告信息?我希望避免添加Suprress警告
标记
类型安全:从对象
到映射
通过在执行强制转换之前检查类型
if(auth.getDetails() instanceof Map){
//here your cast
}
。。。您的问题可能重复至:
你不能
由于只将的返回值定义为对象
,因此必须强制转换,尽管运行时将检查类型映射
,但仍然不能保证它将字符串
映射到字符串
(因为)
这意味着,当使用
映射时,您可能会在稍后的某个时间点获得ClassCastException
。这就是警告试图告诉您的内容,您可以通过添加@SuppressWarnings
来承担责任。如果可能的话,我会感到惊讶。谢谢您的解释。那么正确的使用方法是什么呢?在需要的地方添加@SuppressWarnings(“unchecked”)
。如果您将它添加到语句中,它不会意外地隐藏另一个可能在以后的开发过程中出现的警告案例,如果添加到方法或类中,可能会出现这种情况。尽管对于未经初始化的人来说,这有点让人头疼,但很好地提到了类型擦除
。