Lombok @ExtensionMethod 사용해보기

겔로그·2024년 8월 8일
0

Lombok 라이브러리는 Spring Boot에서 보일러플레이트 코드를 줄이기 위해 많은 사람들이 사용하고 있습니다. @Getter, @Setter, @NoArgsConstructor 등 어노테이션을 기반으로 제공하고 있는데요. 오늘은 @ExtensionMethod에 대해 알아보고자 합니다.

@ExtensionMethod이란?

공식 문서에 따르면 @ExtensionMethod 정의는 다음과 같습니다.

You can make a class containing a bunch of public, static methods which all take at least 1 parameter. These methods will extend the type of the first parameter, as if they were instance methods, using the @ExtensionMethod feature.

예시

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StringUtilsExtensionTest {
    public static boolean isNotBlank(String str) {
        return str != null && !str.isEmpty();
    }
}


@ExtensionMethod(StringUtils.class)
public class Test {
	@Test
    public void test() {
        assertFalse("".isNotBlank());
    }
}

다음과 같이 첫번째 인자가 인스턴스화 될 경우 @ExtensionMethod로 정의한 메소드를 추가로 사용할 수 있습니다.

사용 방법

  1. public static 메소드를 정의합니다.
  2. 확장시킬 클래스 유형을 파라미터로 정의합니다.
  3. 사용할 지점 클래스에 @ExtensionMethod로 커스텀한 클래스를 정의해주고 사용합니다.

결론

일반적으로 사용중인 Wrapper 클래스에 기능이 부족하다고 느끼거나 이런 기능이 추가됐으면 좋겠다는 생각을 하신적이 있을까요?

기능이 제공되지 않을 경우 해당 어노테이션을 사용해보는건 어떨까요?

감사합니다.

profile
Gelog 나쁜 것만 드려요~

0개의 댓글