将List <authority>转换为Spring Security中的Collection <grantedauthority> </grantedauthority> </authority>

时间:2011-10-12 09:39:46

标签: java spring-security

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

更新 当我试图创造:

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

其中user.getAuthorities()返回我定义的Authority对象的arraylist

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

  

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) 

3 个答案:

答案 0 :(得分:4)

javadoc of the User constructor告诉您最后一个参数必须是Collection<? extends GrantedAuthority>。因此,如果它是ArrayList<Something>,其中SomethingGrantedAuthority或实现GrantedAuthority的类,则会接受ArrayList。

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

答案 1 :(得分:0)

List已经 一个Collection,因为它是Collection的子界面。

如果您有实现List的类型变量(例如ArrayList),则可以在预期Collection的任何位置使用它。不需要转换,甚至不需要明确的类型转换。

答案 2 :(得分:0)

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

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