[Java ☕️] Class, System

ConewLog·2024년 8월 5일
0

Java ☕️

목록 보기
5/7

☕️ 김영한의 실전 자바 - 중급 1편 을 수강하며 학습한 내용을 저만의 언어로 정리하고 있습니다.


1. Class 클래스

Class를 통해 자바 애플리케이션 내의 클래스, 인터페이스 메타 데이터를 나타낼 수 있다.

메타 데이터

  • 클래스 이름
  • 생성자 정보
  • 필드 정보
  • 메소드 정보
  • ...

Class 객체를 조회하는 방법

  1. 클래스에서 조회하는 방법

    Class clazz = String.class;
  2. .getClass()로 조회하는 방법

    Class clazz = new String().getClass();
  3. Class.forName(String className)으로 조회하는 방법

    Class clazz = Class.forName("java.lang.String");
  • ClassNotFoundException 예외처리가 필요함에 주의한다.

주요 메서드

1. 필드, 메서드, 부모 클래스, 인터페이스 조회하기

Class clazz = new String().getClass();

Field[] declaredFields = clazz.getDeclaredFields();
Method[] declaredMethods = clazz.getDeclaredMethods();
Class superclass = clazz.getSuperclass();
Class[] interfaces = clazz.getInterfaces();
  • getDeclaredFields(): 클래스의 필드 조회
  • getDelcaredMethods(): 클래스의 메서드 조회
  • getSuperClass(): 클래스의 부모 클래스 조회
  • getInterfaces(): 클래스의 인터페이스 조회

2. 생성자 조회하기

Constructor[] constructors = clazz.getConstructors();
Constructor declaredConstructor = clazz.getDeclaredConstructor();

System.out.println("constructors");
for (Constructor constructor : constructors) {
	System.out.println("constructor = " + constructor);
}
System.out.println("declaredConstructor = " + declaredConstructor);
  • getConstructors(): 모든 public 생성자를 조회

  • getDeclaredCounstroctor(Class<?>... parameterTypes): parameterTypes를 비워두면 인자가 없는 생성자를 조회

  • 생성자를 가져온 뒤 newInstance()를 통해 조회한 생성자를 기반으로 인스턴스를 만들 수 있다.

    String str = (String) declaredConstructor.newInstance();
    • 즉, 런타임에 클래스가 결정되는 경우, newInstance()를 사용하여 동적으로 객체 생성을 할 수 있다는 의미이다.

리플렉션에 사용되는 Class

Class 메타정보를 이용해 메서드, 필드, 생성자를 조회할 수 있었다.
즉, Class를 이용하면 객체를 만들고, 메서드를 호출할 수 있다.
이러한 작업을 통틀어 "리플렉션"이라고 한다.

리플렉션은 런타임에 클래스타입이 정해질 경우, 동적으로 객체를 생성하고 메서드를 호출하는 데 유용하다.


2. System 클래스

System은 시스템 관련 기본 기능을 제공한다.
기본 생성자를 private으로 접근 제한하고 있기에 인스턴스화 할 수 없다.

주요 기능

1. 표준 입력, 출력, 오류 스트림

  • System.in
  • System.out
  • System.err

2. 시간 측정

  • System.currentTimeMillis()
  • System.nanoTime()

3. 환경 변수

  • System.getenv(): 운영체제의 환경 변수를 조회한다.

4. 시스템 속성

  • System.getProperties(): 자바가 사용하는 시스템의 기본적인 환경 설정을 조회한다.

5. 시스템 종료

  • System.exit(int status): 프로그램을 종료한다.
    • 웹 애플리케이션 개발 시에는 System.exit(int status)로 절대 프로그램을 마치지 않는다. 적절한 프로그램 종료 과정을 거치도록 한다.

6. 배열 고속 복사

  • System.arraycopy(Object src,int srcPos, Object dest, int destPos, int length): 배열을 시스템 레벨에서 복사한다. for문을 사용해서 복사하는 것보다 수 배 빠르게 복사할 수 있다.

참고 사이트

profile
코뉴로그

0개의 댓글