com.github.insanusmokrassar.AutoPostTelegramBot.utils.Extractor.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of AutoPostTelegramBot Show documentation
Show all versions of AutoPostTelegramBot Show documentation
It is base library for creating smart bot for simple management of channels posts
package com.github.insanusmokrassar.AutoPostTelegramBot.utils
import com.github.insanusmokrassar.IObjectK.interfaces.IObject
import java.lang.reflect.InvocationTargetException
fun initObject(className: String, params: IObject?): T {
return params ?.let {
extract(className, it)
} ?: {
extract(className)
}()
}
/**
* Return new instance of target class
* @param path Path to package as path.to.package.java
* *
* @param Target class (or interface)
* *
* @return New instance of target class
* *
* @throws IllegalArgumentException
*/
@Throws(IllegalArgumentException::class)
fun extract(path: String, vararg constructorArgs: Any?): T {
val targetClass = getClass(path)
targetClass.constructors.forEach {
if (it.parameterTypes.size != constructorArgs.size) {
return@forEach
}
try {
return it.newInstance(*constructorArgs) as T
} catch (e: InstantiationException) {
throw IllegalArgumentException("Can't instantiate the instance of class: it may be interface or abstract class", e)
} catch (e: IllegalAccessException) {
throw IllegalArgumentException("Can't instantiate the instance of class: can't get access for instantiating it", e)
} catch (e: InvocationTargetException) {
return@forEach
} catch (e: IllegalArgumentException) {
return@forEach
}
}
throw IllegalArgumentException("Can't find constructor for this args")
}
@Throws(IllegalArgumentException::class)
fun getClass(path: String): Class {
try {
val targetClass = Class.forName(path)
return targetClass as Class
} catch (e: ClassNotFoundException) {
throw IllegalArgumentException("Can't find class with this classPath: $path", e)
}
}