fun createObjectByPackageName(packageName: String, className: String): Any? { try { val ...
k
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
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
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
Kotlin reflection is supported on JVM targets only.
k
yeah so far no alternative 😞