3

I am using below code to extract deviceId from Spring Authentication class.

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"));
}

How do I get over of this Type safety warning message? I want to avoid adding Suprress Warnings tag.

Type safety: Unchecked cast from Object to Map<String,String>

Tunaki
  • 116,530
  • 39
  • 281
  • 370
user1950349
  • 3,822
  • 15
  • 47
  • 87

2 Answers2

4

You can't.

Since Authentication simply defines return value of getDetails() as an Object, you have to cast, and although the type Map will be checked at runtime, there is still no guarantee that it maps String to String (because of type erasure).

This means that you may get a ClassCastException at some later point, when the Map is used. That is what the warning is trying to tell you, and you accept responsibility for that by adding @SuppressWarnings.

Andreas
  • 138,167
  • 8
  • 112
  • 195
  • Thanks for the explanation. What is the right way to use it then? – user1950349 Jan 22 '16 at 23:02
  • 1
    Add `@SuppressWarnings("unchecked")` where you want. If you add it to the statement, it won't accidentally hide another case of the warning that may occur later on during development, which could be the case if added to method or class. – Andreas Jan 22 '16 at 23:10
  • Although it's a bit of a brain-ache for the uninitiated,nice mention of `type erasure`. – jumping_monkey Dec 23 '19 at 04:38
1

By checking the type before performing a cast.

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

... your question may be a duplicate to: Type safety: Unchecked cast

Community
  • 1
  • 1
Jarlik Stepsto
  • 1,366
  • 7
  • 16