2024
[Java] 람다 - 함수형 인터페이스
키보드발
2024. 1. 24. 02:31
시큐리티를 공부하다가 생소한 표현이 있어서 찾아보게되었다.
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
user.getRoleList().forEach(r->{
authorities.add(()->r);
});
return authorities;
}
authorities.add(()->r);
람다 표현식을 자주 사용하왔지만 Collection에 쓰는 것은 처음이였기 때문이다.
먼저 GrantedAuthority에 대해서 알아야한다.
해당 클래스는 인터페이스다. 인터페이스를 사용하기 위해서는 구현체 클래스가 필요하다.
public interface GrantedAuthority extends Serializable {
String getAuthority();
}
람다를 사용하지 않고 일반적으로 구현한다면 다음과 같다.
직접 구현클래스르 작성하는 것이다.
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
user.getRoleList().forEach(r->{
authorities.add(new GrantedTest(r));
});
return authorities;
}
public static class GrantedTest implements GrantedAuthority{
private String auth;
public GrantedTest(String auth) {
this.auth = auth;
}
@Override
public String getAuthority() {
return auth;
}
}
익명 클래스를 통해서 코드를 간소화 할 수 있다.
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
user.getRoleList().forEach(r->{
authorities.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return null;
}
});
});
return authorities;
}
익명 클래스는 인터페이스 구현클래스를 따로 생성하지 않고 인터페이스를 구현할 수 있기 때문에 매우 유용하다.
이 코드를 더 간소화 할 수 있다.
-> 람다를 사용하면 가능하다.
하지만 주의해야할 것은 람다를 통해서 인터페이스를 구현할때는 오버라이드 해야하는 메소드가 하나여야만 한다.
위와 같은 케이스는 오버라이드해야하는 메소드가 하나이기때문에 람다를 통해서 간소화가 가능하다.
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
user.getRoleList().forEach(r->
authorities.add(() -> r)
);
return authorities;
}