简体   繁体   English

列表中的Lambda表达式不起作用

[英]Lambda expression in a List not working

I am working in a Java application with Java 8, using the stream functionality I have this POJO: 我正在使用Java 8在Java应用程序中工作,使用流功能有以下POJO:

public class Authority implements GrantedAuthority {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private final String authority;

    public Authority(String authority) {

        this.authority = authority;
    }


    @Override
    public String getAuthority() {
        return authority;
    }


    @Override
    public String toString() {
        return "Authority [authority=" + authority + "]";
    }
}

and

public class User implements Serializable, UserDetails {

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
        return authorities;
    }

    public boolean isAdmin() {
        return getAuthorities().stream().filter
            (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }
}

and I've created this Junit to check if everything os OK 我创建了这个Junit来检查一切是否正常

  @Test
    public void isAdminTests() {

        User adminUser = UserUtils.createBasicUser("user2@gmail.com", "user2@gmail.com", true);
        Set<UserRole> adminUserRoles = new HashSet<>();
        adminUserRoles.add(new UserRole(adminUser, new Role(RolesEnum.ADMIN)));
        adminUser.getUserRoles().addAll(adminUserRoles);

        System.out.print(adminUser.getAuthorities());

        assertTrue (adminUser.isAdmin()); 

    }

and this is the value in the console: 这是控制台中的值:

[Authority [authority=ROLE_ADMIN]]

But I have an assertion error 但是我有一个断言错误

My guess is that you compare the Authority Object (which is a String IIRC) with the enum object 我的猜测是,您将授权对象(是字符串IIRC)与枚举对象进行了比较

o.getAuthority().equals(RolesEnum.ADMIN))

You have to compare these two diffrent objects so that a match is possible 您必须比较这两个不同的对象,以便可能进行匹配

You could try 你可以试试

o.getAuthority().equals(RolesEnum.ADMIN.name()))

when you can ensure that the enum names always are the same as the role names. 您可以确保枚举名称始终与角色名称相同。

Not sure, but try this: 不知道,但是尝试这个:

here 这里

public boolean isAdmin () {
        return getAuthorities().stream().filter
                (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }

change to smth like this: 改成这样:

o.getAuthority().equals(new GrantedAuthority(RolesEnum.Admin.name()))).findFirst().isPresent();

Because when you creating spring authorities "ROLE_" is added by default as a prefix to your String role representation 因为在创建弹簧授权时,默认情况下会在字符串角色表示形式的前缀中添加“ ROLE_”作为前缀

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM