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

main.name.remal.gradle_plugins.dsl.extensions.java.lang.reflect.Method.kt Maven / Gradle / Ivy

The newest version!
package name.remal.gradle_plugins.dsl.extensions

import name.remal.isPublic
import name.remal.isStatic
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method

@Suppress("DEPRECATION")
fun Method.makeAccessible() = apply {
    if (isAccessible) return@apply
    if (!isPublic || !declaringClass.isPublic) {
        isAccessible = true
    }
}

fun  Method.invokeForInstance(instance: Any, vararg args: Any?): T {
    if (isStatic) throw IllegalStateException("Should be invoked statically: $this")
    makeAccessible()
    try {
        @Suppress("UNCHECKED_CAST")
        return invoke(instance, *args) as T
    } catch (e: InvocationTargetException) {
        throw e.cause ?: e
    }
}

fun  Method.invokeStatically(vararg args: Any?): T {
    if (!isStatic) throw IllegalStateException("Should NOT be invoked statically: $this")
    makeAccessible()
    try {
        @Suppress("UNCHECKED_CAST")
        return invoke(null, *args) as T
    } catch (e: InvocationTargetException) {
        throw e.cause ?: e
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy