All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.insanusmokrassar.AutoPostTelegramBot.utils.Extractor.kt Maven / Gradle / Ivy

Go to download

It is base library for creating smart bot for simple management of channels posts

There is a newer version: 1.7.0
Show newest version
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)
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy