如何将 UnmodifiableRandomAccessList 设置为 java 中的 Set<Object>
How to set UnmodifiableRandomAccessList to Set<Object> in java
有一个包含用户权限的 Oauth2Authentication 对象。当我想获得它的权限并将其设置为用户对象的权限时,如下所示:
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
LinkedHashMap linkedHashMap = (LinkedHashMap) oAuth2Authentication.getUserAuthentication().getDetails();
user.setAuthorities((Set<GrantedAuthority>) oAuth2Authentication.getAuthorities());
引发了以下异常:
java.lang.ClassCastException:
java.util.Collections$UnmodifiableRandomAccessList cannot be cast to
java.util.Set
我该如何解决?
注:
Authorities of User 对象的类型是 Set<GrantedAuthority>
如果 oAuth2Authentication.getAuthorities()
是 List
,您可以轻松地从中创建 Set
:
user.setAuthorities(new HashSet<GrantedAuthority>(oAuth2Authentication.getAuthorities()));
请注意 GrantedAuthority
应该有 hashCode()
和 equals()
的正确实现,以便用作 HashSet
.
的成员
有一个包含用户权限的 Oauth2Authentication 对象。当我想获得它的权限并将其设置为用户对象的权限时,如下所示:
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
LinkedHashMap linkedHashMap = (LinkedHashMap) oAuth2Authentication.getUserAuthentication().getDetails();
user.setAuthorities((Set<GrantedAuthority>) oAuth2Authentication.getAuthorities());
引发了以下异常:
java.lang.ClassCastException: java.util.Collections$UnmodifiableRandomAccessList cannot be cast to java.util.Set
我该如何解决?
注:
Authorities of User 对象的类型是 Set<GrantedAuthority>
如果 oAuth2Authentication.getAuthorities()
是 List
,您可以轻松地从中创建 Set
:
user.setAuthorities(new HashSet<GrantedAuthority>(oAuth2Authentication.getAuthorities()));
请注意 GrantedAuthority
应该有 hashCode()
和 equals()
的正确实现,以便用作 HashSet
.