fun createObjectByPackageName(packageName: String, className: String): Any? {
try {
val fullClassName = "$packageName.$className"
val clazz = Class
return clazz.newInstance()
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InstantiationException) {
e.printStackTrace()
}
return null
}
is there a pure kotlin implementation of this ?
t
Thomas Urbanitsch
09/04/2023, 10:49 AM
afaik there is no multiple exception catching like in Java (yet) (also not sure if that is your main question here)
i guess you could do something like this:
Copy code
fun createObjectByPackageName(packageName: String, className: String): Any? {
return try {
Class
.forName("$packageName.$className")
.getDeclaredConstructor().newInstance()
} catch (e: Exception) {
when(e) {
is ClassNotFoundException,
is IllegalAccessException,
is InstantiationException -> e.printStackTrace()
else -> throw e
}
null
}
}
or write your own multicatch extension 🤷
(disclaimer: i didn’t try this 😅 )
(also not sure how this is related to multiplatform?)
k
Kashismails
09/04/2023, 10:51 AM
basically Class.forname is a java function we have been using the above function for a while now we are moving it kotlin multiplatform and apparently there is no alternative of this in kotlin 😞
i
iXPert12
09/04/2023, 11:36 AM
Kotlin reflection is supported on JVM targets only.