티스토리 뷰

공부

[kotlin] ReflectionUtils.kt

승가비 2022. 7. 9. 20:22
728x90
package com.tistory.seunggabi.util

import java.lang.reflect.Constructor

object ReflectionUtils {
    fun <T> new(clazz: Class<T>, vararg args: Any?): T {
        val list = if (args.isEmpty()) {
            emptyList()
        } else {
            args.asList()
        }

        @Suppress("UNCHECKED_CAST")
        val parameters = parameters(list as List<Any>)

        @Suppress("SpreadOperator")
        val constructor = clazz.getConstructor(*parameters)

        return new(constructor, list)
    }

    private fun parameters(args: List<Any>): Array<Class<*>> {
        return args
            .map {
                it::class.java
            }
            .toTypedArray()
    }

    private fun <T> new(constructor: Constructor<T>, args: List<Any?>): T {
        constructor.isAccessible = true

        @Suppress("SpreadOperator")
        return constructor.newInstance(*args.toTypedArray())
    }
}
package com.tistory.seunggabi.util

import jdk.jshell.spi.ExecutionControl.NotImplementedException
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test


internal class ReflectionUtilsTest {
    class MockClass(private val args: String) {
        fun f() {
            throw NotImplementedException(args)
        }
    }

    companion object {
        private val CLAZZ = MockClass::class.java
    }

    @Test
    fun new() {
        // given
        val should = "Custom Exception"

        // when
        val actual = ReflectionUtils.new(CLAZZ, should)

        // then
        assertThat(actual).isExactlyInstanceOf(CLAZZ)
        assertThatThrownBy { actual.f() }
            .isInstanceOf(NotImplementedException::class.java)
            .hasMessage(should)
    }
}

https://stackoverflow.com/questions/46674787/instanceclass-java-vs-instance-javaclass

 

instance::class.java vs. instance.javaClass

Given Kotlin 1.1. For an instance of some class, instance::class.java and instance.javaClass seem to be nearly equivalent: val i = 0 println(i::class.java) // int println(i.javaClass) // int print...

stackoverflow.com

 

728x90

'공부' 카테고리의 다른 글

[JPA] manual SQL (nativeQuery=True)  (0) 2022.07.10
[js] npm(직렬) vs yarn(병렬)  (0) 2022.07.10
[js] axios  (0) 2022.07.09
[js] package.json "lint": "eslint '**/*.{js,jsx}' --quiet"  (0) 2022.07.09
[kotlin] list to map  (0) 2022.07.09
댓글