2016-01-22 57 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

相關問題