Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[둘리] 1단계 자동 DI 미션 제출합니다 #5

Merged
merged 18 commits into from
Sep 5, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor: java reflection -> kotlin reflection으로 수정
  • Loading branch information
hyemdooly committed Sep 5, 2023
commit ddfe49ae1a063229b817eee956a5179698914fb3
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,19 @@ package woowacourse.shopping.ui.common

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.jvmErasure

class ViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val constructor = modelClass.declaredConstructors.first()
val constructor = modelClass::class.primaryConstructor
requireNotNull(constructor) { "Unknown ViewModel Class $modelClass" }
val params = constructor.parameters

val types = constructor.parameterTypes
val params = mutableListOf<Any?>()

val properties = Container::class.java.declaredFields
for (type in types) {
val field = properties.first { it.type == type }
?: throw IllegalArgumentException("Can't find Property $type")
field.isAccessible = true
params.add(field.get(null))
val instances = params.map {
Container.getInstance(it.type.jvmErasure)
}

return constructor.newInstance(*params.toTypedArray()) as T
return constructor.call(*instances.toTypedArray()) as T
}
}