개발/자바

java : import static

피터JK 2025. 2. 18. 10:17
728x90

import static은 Java에서 특정 클래스의 static 멤버(메서드 또는 변수)를 가져와서 클래스 이름 없이 직접 사용할 수 있도록 해주는 기능입니다.

📌 기본 문법

import static 패키지명.클래스명.멤버이름;

또는

import static 패키지명.클래스명.*;

와일드카드 *를 사용하면 해당 클래스의 모든 static 멤버를 가져올 수 있습니다.


📌 사용 예시

1️⃣ import static 없이 사용

public class MathExample {
    public static void main(String[] args) {
        double result = Math.sqrt(25);  // Math 클래스 이름을 사용해야 함
        System.out.println(result);
    }
}

2️⃣ import static 사용

import static java.lang.Math.sqrt;

public class MathExample {
    public static void main(String[] args) {
        double result = sqrt(25);  // 클래스 이름 없이 바로 사용 가능
        System.out.println(result);
    }
}

📌 import static의 활용 예시

1️⃣ java.lang.Math의 static 메서드 활용

import static java.lang.Math.*;

public class StaticImportExample {
    public static void main(String[] args) {
        System.out.println(sqrt(16));   // Math.sqrt() 대신 sqrt()로 사용 가능
        System.out.println(pow(2, 3));  // Math.pow() 대신 pow() 사용
        System.out.println(PI);         // Math.PI 대신 PI 사용
    }
}

2️⃣ java.util.concurrent.TimeUnit 활용

import static java.util.concurrent.TimeUnit.SECONDS;

public class TimeUnitExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("3초 대기...");
        Thread.sleep(SECONDS.toMillis(3));  // SECONDS를 직접 사용
        System.out.println("완료!");
    }
}

3️⃣ org.junit.Assert 활용 (JUnit 테스트 코드)

import static org.junit.Assert.assertEquals;

public class TestExample {
    public static void main(String[] args) {
        int expected = 5;
        int actual = 2 + 3;
        assertEquals(expected, actual);  // Assert.assertEquals() 대신 바로 사용 가능
    }
}

📌 import static의 장점과 단점

✅ 장점

  • 코드가 간결해짐 (Math.sqrt(25) → sqrt(25))
  • 가독성이 높아질 수 있음 (특히 수학 계산, 테스트 코드에서 유용)

❌ 단점

  • 어느 클래스의 메서드인지 명확하지 않을 수 있음
  • 과도한 사용 시 코드 가독성이 떨어질 수 있음 (특히 여러 개의 import static을 사용하면 충돌 가능)

📌 언제 사용해야 할까?

추천 사용 예시

  • 수학 관련 연산 (Math.PI, Math.sqrt() 등)
  • JUnit 테스트에서 assertEquals, assertTrue 등 자주 쓰이는 메서드
  • java.util.concurrent.TimeUnit.SECONDS처럼 가독성을 높이는 경우

사용을 지양해야 하는 경우

  • 코드의 가독성을 해칠 가능성이 높은 경우
  • 충돌이 발생할 수 있는 경우 (예: 여러 클래스에서 동일한 이름의 static 메서드가 있을 때)

🔥 결론

  • import static은 특정 static 멤버를 자주 사용할 때 유용하지만, 너무 남발하면 가독성이 떨어질 수 있으므로 적절히 활용하는 것이 중요합니다. 
728x90