[Java] Chapter 12. java.base 모듈

SeungWoo Cha·2025년 9월 11일

[Java] 이것이 자바다

목록 보기
10/17

Chapter 12. java.base 모듈

12.1. API 도큐먼트

  • API 도큐먼트: 자바 라이브러리를 쉽게 찾고 사용하는 방법 제공

  • 주요 구성

    1. 클래스 선언부 확인

    2. 멤버 보기 (SUMMARY)

      • NESTED: 중첩 클래스/인터페이스
      • FIELD: 필드 목록
      • CONSTR: 생성자 목록
      • METHOD: 메소드 목록
    3. 메소드 필터

      • All Methods, Static Methods, Instance Methods, Concrete Methods, Deprecated Methods

12.2. java.base 모듈

  • 모든 모듈이 의존하는 기본 모듈 (requires 없이 사용 가능)

  • 주요 패키지

    • java.lang : 기본 클래스 (System, String, Integer …)
    • java.util : 자료구조, 유틸 (Scanner, Collections …)
    • java.text : 날짜/숫자 포맷
    • java.time : 날짜/시간 처리
    • java.io : 입출력 스트림
    • java.net : 네트워크 통신
    • java.nio : 버퍼 및 NIO 입출력

12.3. Object 클래스

  • 모든 클래스의 최상위 부모

  • 주요 메소드

    • equals(Object obj) : 객체 동등 비교
    • hashCode() : 객체 해시코드 반환
    • toString() : 객체 문자열 정보
class Student {
    int no;
    String name;

    // equals 재정의
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Student s) {
            return no == s.no && name.equals(s.name);
        }
        return false;
    }

    // hashCode 재정의
    @Override
    public int hashCode() {
        return no + name.hashCode();
    }

    // toString 재정의
    @Override
    public String toString() {
        return "학생번호: " + no + ", 이름: " + name;
    }
}
  • 레코드 (Java 14~)
public record Person(String name, int age) {}

자동으로 private final 필드, 생성자, getter, equals, hashCode, toString 생성

  • Lombok 예시
import lombok.Data;

@Data
public class User {
    private String id;
    private String name;
}

12.4. System 클래스

  • 운영체제 일부 기능 접근

  • 주요 필드: System.out, System.err, System.in

  • 주요 메소드:

    • exit(int status) : 프로세스 종료 (0=정상)
    • currentTimeMillis(), nanoTime() : 시간 측정
    • getProperty(), getenv() : 시스템 속성/환경 변수 조회
System.out.println(System.currentTimeMillis());
System.out.println(System.nanoTime());

System.out.println(System.getProperty("os.name"));
System.out.println(System.getenv("PATH"));
  • 키보드 입력
int key = System.in.read();
System.out.println("입력된 키 코드: " + key);

12.5. 문자열 클래스

1. String

byte[] arr = "안녕".getBytes("UTF-8");
String str = new String(arr, "UTF-8");

2. StringBuilder (문자열 수정에 유리)

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, " Java");
System.out.println(sb.toString());

3. StringTokenizer (구분자 기반 분리)

String text = "apple,banana,grape";
StringTokenizer st = new StringTokenizer(text, ",");
while (st.hasMoreTokens()) {
    System.out.println(st.nextToken());
}

12.6. 포장 클래스

  • 기본 타입을 객체로 감싸는 클래스 (Integer, Double 등)
  • 박싱 / 언박싱
Integer obj = 100;   // 박싱
int value = obj;     // 언박싱
  • 문자열 → 기본 타입 변환
int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
  • 비교 주의
Integer a = new Integer(100);
Integer b = new Integer(100);

System.out.println(a == b);       // false (주소 비교)
System.out.println(a.equals(b));  // true  (값 비교)

12.7. 수학 클래스 (Math & Random)

  • Math 클래스의 메서드는 모두 정적(static) → 객체 생성 없이 바로 사용 가능.

  • 주요 메서드:

    • abs(x), ceil(x), floor(x), max(a,b), min(a,b), random(), round(x)
System.out.println(Math.abs(-10));    // 10
System.out.println(Math.ceil(3.2));   // 4.0
System.out.println(Math.floor(3.7));  // 3.0
System.out.println(Math.max(5, 9));   // 9
System.out.println(Math.random());    // 0.0 <= ~ < 1.0

java.util.Random

  • 난수 생성을 위한 클래스

  • 생성자

    • new Random() : 현재 시간 기반 seed
    • new Random(long seed) : 지정된 seed
  • 주요 메서드

    • nextBoolean()
    • nextDouble()
    • nextInt()
    • nextInt(int n) : 0 ≤ 값 < n
Random rand = new Random();
System.out.println(rand.nextBoolean()); // true/false
System.out.println(rand.nextInt(10));   // 0~9

12.8. 날짜와 시간 클래스

Date

Date now = new Date();
System.out.println(now.toString()); // 기본 형식 출력

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
System.out.println(sdf.format(now)); // 원하는 형식 출력

Calendar

Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
  • 다른 시간대(Calendar)
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar laTime = Calendar.getInstance(tz);

LocalDateTime (java.time 패키지)

  • 조작 : plusXxx(), minusXxx()
  • 비교 : isAfter(), isBefore(), isEqual()
  • 생성 : now(), of(year, month, day, hour, min, sec)
LocalDateTime now = LocalDateTime.now();
LocalDateTime future = now.plusDays(5);

System.out.println(now.isBefore(future)); // true

12.9. 형식 클래스

  • 숫자 형식화
DecimalFormat df = new DecimalFormat("#,###.0");
System.out.println(df.format(1234567.89)); // 1,234,567.9
  • 날짜 형식화
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일");
System.out.println(sdf.format(new Date()));

12.10. 정규 표현식 클래스

  • 문자열 검증에 사용
boolean result = Pattern.matches("[0-9]{3}-[0-9]{4}", "123-4567");
System.out.println(result); // true

12.11. 리플렉션 (Reflection)

  • 클래스, 인터페이스의 메타 정보(패키지, 필드, 메서드 등) 에 접근하고 조작 가능.

Class 객체 얻기

Class clazz1 = Car.class;
Class clazz2 = Class.forName("com.example.Car");
Car car = new Car();
Class clazz3 = car.getClass();

메타 정보 확인

System.out.println(clazz1.getPackage().getName());   // 패키지명
System.out.println(clazz1.getSimpleName());          // 클래스명
System.out.println(clazz1.getName());                // 전체 경로

생성자/메서드 정보

Method[] methods = clazz1.getDeclaredMethods();
for(Method method : methods){
    System.out.println(method.getName());
}

리소스 경로 얻기

String path = clazz1.getResource("config.xml").getPath();
InputStream is = clazz1.getResourceAsStream("config.xml");

12.12. 어노테이션 (Annotation)

  • 코드의 메타데이터를 제공 (@ 기호 사용)

정의 및 용도

  1. 컴파일 정보 전달 (@Override)
  2. 빌드 시 코드 생성
  3. 실행 시 기능 처리

작성

public @interface MyAnnotation {
    String value();
    int number() default 1;
}

적용 대상 (@Target)

@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {}

유지 정책 (@Retention)

  • SOURCE / CLASS / RUNTIME
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}

어노테이션 활용

Method[] methods = Service.class.getDeclaredMethods();
for(Method method : methods){
    if(method.isAnnotationPresent(PrintAnnotation.class)){
        PrintAnnotation pa = method.getAnnotation(PrintAnnotation.class);
        System.out.println(pa.value());
    }
}
profile
한 발자국씩

0개의 댓글