빰_s
(22.06.08)(Spring) 정적 임포트 : Static Import 본문
JDK 1.5부터 추가된 기능.
import 문을 사용하면 클래스의 패키지명을 생략할 수 있는 것과 같이
(ex. import java.lang.Math; => Math.max(a,b) // java.lang 을 생략할 수 있음.)
static import를 사용하면 static 멤버를 호출할 때 클래스명을 생략할 수 있음.
아래는 그 예시를 보자.
import static java.lang.Integer.*; // Integer 클래스의 모든 static 멤버
import static java.lang.Math.random; // Math.random()만 import. 괄호는 붙이지 않는다.
import static java.lang.System.out; // 이렇게 하면 System.out을 out만으로 참조 가능
위와 같이 static 을 추가한 채로 import를 사용할 수 있다.
// static import문 선언 전
System.out.println(Math.random());
만약 java.lang.System.out; 클래스를 static 없이 import 하게 된다면, System.out.println() 문을 써야 하지만,
// static import문 선언 후
out.println(random());
static을 추가하고 import하게 되면 System 없이 out.println()으로만 해당 기능을 사용할 수 있다.
마치 현재 클래스의 멤버인 것처럼 유연하게 사용할 수 있지만, 그만큼 혼동을 주기 쉽다는 단점도 존재한다.
사용의 예시로는 AssertJ를 static Import하게 되면 AssertThat.().~~~ 와 같이 간결한 코드만으로 Junit Test를 진행할 수 있다.
import static org.assertj.core.api.Assertions.*;
assertThat(findMember.getId()).isEqualTo(member.getId());
assertThat(findMember.getUsername()).isEqualTo(member.getUsername());
assertThat(findMember).isEqualTo(member);
(※ 참조 사이트)
[JAVA] static import문
static import문은 JDK1.5부터 추가된 기능이다. import문을 사용하면 클래스의 패키지명을 생략할 수 있는 것과 같이 static import문을 사용하면 static멤버를 호출할 때 클래스명을 생략할 수 있다. 코드
atoz-develop.tistory.com
'Java > Spring' 카테고리의 다른 글
(25.01.13) API (0) | 2025.01.13 |
---|---|
(24.12.29) 카카오 로그인 구현(Rest API, Spring Boot) : 밑준비 (1) | 2024.12.29 |
(24.12.17) WebClient 정리 (2) | 2024.12.16 |
(22.06.08)(Spring) 테스트 코드 작성을 도와주는 라이브러리, AssertJ (1) | 2022.06.09 |
[H2 Database] The write format 1 is smaller than the supported format 2 (1) | 2022.03.14 |
Comments