☕️ 김영한의 실전 자바 - 중급 1편 을 수강하며 학습한 내용을 저만의 언어로 정리하고 있습니다.
Class
를 통해 자바 애플리케이션 내의 클래스, 인터페이스 메타 데이터를 나타낼 수 있다.
메타 데이터
클래스에서 조회하는 방법
Class clazz = String.class;
.getClass()
로 조회하는 방법
Class clazz = new String().getClass();
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
를 이용하면 객체를 만들고, 메서드를 호출할 수 있다.
이러한 작업을 통틀어 "리플렉션"이라고 한다.
리플렉션은 런타임에 클래스타입이 정해질 경우, 동적으로 객체를 생성하고 메서드를 호출하는 데 유용하다.
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문을 사용해서 복사하는 것보다 수 배 빠르게 복사할 수 있다.