본문 바로가기

프로그래밍언어/Java

[Java 중급] Class 클래스

Class 클래스


클래스의 정보(메타데이터)를 다루는데 사용. 실행 중인 자바 애플리케이션 내에서 필요한 클래스의 속성과 메서드에 대한 정보를 조회하고 조작할 수 있다. 

  • 클래스의 이름, 슈퍼클래스, 인터페이스, 접근제한자 등과 같은 정보 조회
  • 리플렉션: 클래스에 정의된 메서드, 필드, 생성자 등을 조회
  • 동적 로딩과 생성: Class.forName() 메서드를 사용하여 클래스를 동적으로 로드하고, 새로운 인스턴스를 생성할 수 있다. 
  • 어노테이션 처리 
package lang.clazz;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ClassMetaMain {
    public static void main(String[] args) throws Exception {
        //Class 조회
        Class clazz = String.class; // 1. 클래스에서 조회
        // Class clazz1 = new String().getClass(); // 2. 인스턴스에서 조회
        // Class clazz2 = Class.forName("java.lang.String");// 3. 문자열로 조회

        // 모든 필드 출력
        Field[] declaredFields = clazz.getDeclaredFields();

        for (Field field : declaredFields) {
            System.out.println("field: " + field.getName());
        }

        //모든 메서드 출력
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println("method: " + method.getName());
        }

        // 상위 클래스 정보 출력
        System.out.println("SuperClass: " + clazz.getSuperclass().getName());
        
        // 인터페이스 정보 출력
        Class[] interfaces = clazz.getInterfaces();
        for (Class anInterface : interfaces) {
            System.out.println("interface: " + anInterface.getName());
        }

    }
}

 

 

=> 

  • getDeclaredFields() : 클래스의 모든 필드 조회
  • getDeclaredMethods() : 클래스의 모든 메서드 조회
  • getSuperClass() : 클래스의 부모 클래스 조회
  • getInterfaces() 클래스의 모든 인터페스 조회

 

클래스 생성하기


public class ClassCreateMain {
    public static void main(String[] args) throws Exception {

        Class helloClass = Hello.class;
        //Class helloClass = Class.forName("lang.clazz.Hello");

        Hello hello = (Hello) helloClass.getDeclaredConstructor().newInstance();
        String result = hello.hello();
        System.out.println("hello = " +hello );
        System.out.println("result = " + result );
        
    }
}

 

리플렉션 - reflection

Class를 사용하면 클래스의 메타 정보를 기반으로 클래스에 정의된 메서드, 필드, 생성자 등을 조회하고 이를 통해 객체의 인스턴스를 생성하거나 메서드를 호출하는 작업을 할 수 있는데 이를 리플렉션이라 한다. 

 

 

 

 

* 인프런 '김영한의 실전 자바 - 중급 1편'을 참고하여 작성하였습니다.