java 在 Spring Security 中将 List<Authority> 转换为 Collection<GrantedAuthority>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7738071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:12:50  来源:igfitidea点击:

Convert List<Authority> to Collection<GrantedAuthority> in Spring Security

javaspring-security

提问by Mahmoud Saleh

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 ?

我的情况是,我有一个采用 Collection 的方法,当我尝试将列表值添加到集合参数中时,我将该值作为列表,但它不起作用,所以我应该转换它吗?

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

其中 user.getAuthorities() 返回我定义的 Authority 对象的数组列表

above code gives error that the constructor is undefined, when i add collection casting it works fine.

上面的代码给出了构造函数未定义的错误,当我添加集合转换时它工作正常。

org.springframework.security.core.userdetails
Class User

Constructor

org.springframework.security.core.userdetails
类用户

构造函数

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

回答by JB Nizet

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

User 构造函数javadoc告诉您最后一个参数必须是Collection<? extends GrantedAuthority>. 因此,如果 ArrayList 是ArrayList<Something>, where SomethingisGrantedAuthority或实现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?

您仍然没有告诉我们方法返回的确切类型是什么user.getAuthorities()。你了解泛型吗?你读过关于泛型Java 教程吗?

回答by NPE

A Listalready isa Collectionsince it's a sub-interface of Collection.

AList已经aCollection因为它是Collection.

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

如果您有一个实现类型的变量List(例如ArrayList),您可以在Collection预期的任何地方使用它。不需要转换,甚至不需要显式类型转换。

回答by Malcolm

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

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

但是,List 已经是集合,所以实际上不需要转换。