开发者

Convert List<Authority> to Collection<GrantedAuthority> in Spring Security [closed]

开发者 https://www.devze.com 2023-04-12 16:27 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

My case is that i have a method that takes Collection and i have the value as a list when i tried to add the list value into collection parameter it doesn't work, so should i cast it ?

UPDATE: when i tried to create:

new org.springframework.security.core.userdetails.User(
                user.getEmail(), user.getPassword(), true, true, true, true,
                user.getAuthorities());

where user.getAuthorities() returns an arraylist of my defined Authority object

above code gives error that the constructor is undefined, when i add collection casting it wor开发者_运维技巧ks fine.

org.springframework.security.core.userdetails

Class User

Constructor

User(java.lang.String username, java.lang.String password, 
boolean enabled, boolean accountNonExpired, 
boolean credentialsNonExpired, boolean accountNonLocked, 
java.util.Collection<? extends GrantedAuthority> authorities) 


The javadoc of the User constructor tells you that the last argument must be a Collection<? extends GrantedAuthority>. So, you ArrayList will be accepted if it's an ArrayList<Something>, where Something is GrantedAuthority or a class which implements GrantedAuthority.

You still haven't told us what was the exact type returned by the method user.getAuthorities(). Do you understand Generics? Have you read the Java tutorial about generics?


A List already is a Collection since it's a sub-interface of Collection.

If you have a variable of type implementing List (e.g. ArrayList), you can use it anywhere a Collection is expected. No conversion will be necessary, not even an explicit type cast.


Collection<SomeClass> collection = list; //Where list is a List<SomeClass>

However, List already is collection, so actually no conversion is required.

0

精彩评论

暂无评论...
验证码 换一张
取 消