IT'S DO
Published 2023. 10. 27. 15:57
리플렉션이란? 개념 정리
728x90

인터넷을 떠돌다가 리플렉션이라는 단어가 있었다. 처음에 이 단어가 무슨 뜻인지 몰랐으나, 찾으면서 알게되어서

용어 정리해놓으면 좋을거 같아서 쓰게 되었다.

 

# 리플렉션은 도구이다.

 

# 예를 들면

 

    public class SampleService {
    public void printMessage(String message) {
        System.out.println(message);
    }
}

 

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

        // SampleService 클래스의 인스턴스 생성
        SampleService sampleService = new SampleService();

        try {
            // SampleService 클래스의 printMessage 메서드를 리플렉션으로 가져옴
            Method method = sampleService.getClass().getMethod("printMessage", String.class);

            // 메서드 호출
            method.invoke(sampleService, "Hello, Reflection!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

위와 같이 소스에서 getMthod를 보면 해당 부분들을 가져올 수 있다. 

즉 간단하게 표현하면  -> get, set, getInterfaces와 같은 도구이다.

 

정의를 보면 자바에서 클래스와 그 클래스의 멤버(메서드, 필드, 생성자 등)을 다루는 방법을 제공하는 API라고 한다. 

이것은 함수가 아닌, 클래스나 메서드 등을 다루는 방법이라고 한다.

 

profile

IT'S DO

@멋진놈

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!