본문 바로가기
서버 개발/Kotlin & Java

Kotlin Reflection

by 그린코드 2021. 12. 19.
  • Reflection이란?

런타임 시에 프로그램 내부의 구조적인 정보를 얻거나, 구조를 수정하는 것이 가능하게 하는 기술입니다.

더보기
더보기
더보기

Reflection is a set of language and library features that allows you to introspect the structure of your program at runtime. Functions and properties are first-class citizens in Kotlin, and the ability to introspect them (for example, learning the name or the type of a property or function at runtime) is essential when using a functional or reactive style.

 

 

코틀린은 kotlin-reflect.jar에 해당 기능이 구현되어 있습니다.

간단하게는 class refrences기능을 사용하여 클래스 정보를 가져올 수 있는데, 가져온 인스턴스의 타입은 자바와 다른 KClass타입입니다.

val c: KClass<MyClass> = MyClass::class

 코틀린 컴파일러가 컴파일 시 메타정보를(@MetaData) 클래스 파일에 추가하고, 필요할 때 해당 정보를 불러옴으로써 Reflection 처리가 가능하게 합니다.

 

 

  • Usage

Dependency Injection, Data binding, Convention over configuration 등에 Reflection 기술이 사용되며, 이것을 활용하면

  1. Class & Type : 멤버, 슈퍼타입 등의 정보를 가져오거나 인스턴스 생성
  2. Methods/Fields : 파라미터 정보, 타입 등을 가져오거나 메서드 실행
  3. 인스턴스 : 클래스 정보 가져오기

등의 기능을 수행할 수 있게 됩니다.

 

간단하게 작성해 본 샘플코드는 아래와 같습니다.

data class Person (val name: String, val age: Int) {
    fun printAllProps() {
        println("name: ${name}, age: $age")
    }
}

fun main() {
    // 클래스 정보 가져오기
    val personClass: KClass<Person> = Person::class
    println(personClass.simpleName) // Person

    // 인스턴스 생성 & 메서드 호출
    val constructor = personClass.primaryConstructor
    val params = listOf("Yoon", 10)
    val personInstance = constructor?.call(*params.toTypedArray())
    personInstance?.printAllProps() // name: Yoon, age: 10

    // 인스턴스로부터 클래스정보 가져오기
    println(personInstance?.javaClass?.simpleName) // Person

    // java lang
    val person = Class.forName("com.example.demo.Person")
    println(person.simpleName) // Person
}

 

'서버 개발 > Kotlin & Java' 카테고리의 다른 글

[Kotlin] Char타입을 Int로 변환하는 방법  (0) 2020.06.23

댓글