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
相关产品推荐
相关产品推荐

