You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot代码中`()->user.getRole().getKey()`lambda对应的原始写法是什么?

这段lambda对应的是非lambda的匿名内部类实现,因为GrantedAuthority是Spring Security提供的函数式接口,仅包含一个抽象方法getAuthority(),所以可以用lambda简写。

完整的等价非lambda写法如下:

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    Collection<GrantedAuthority> collection = new ArrayList<GrantedAuthority>();
    collection.add(new GrantedAuthority() {
        @Override
        public String getAuthority() {
            return user.getRole().getKey();
        }
    });
    return collection;
}

原理说明:

  • GrantedAuthority是Spring Security提供的权限抽象接口,JDK8之后被标记为函数式接口,仅存在一个需要实现的getAuthority()方法
  • lambda写法()-> user.getRole().getKey()本质是省略了匿名类创建、方法重写的样板代码,直接声明方法的返回值逻辑

内容的提问来源于stack exchange,提问作者JB P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:48:02