jeudi 25 juillet 2019

Scala reflection to cast using return type of method at runtime

I am using reflection in scala and i want to generalize the code to cast object to return type of another method which is identified at runtime using reflection

I have tried to get return type of method using reflection but not able to use this in asInstance[] cast operation.

import java.lang.reflect.Modifier
object Test5 {

  def main(args: Array[String]): Unit = {
    val runtimeClass = Class.forName("ConvertToUpper")
    invokeRuntimeMethod(runtimeClass, "toUpper")
  }

  def invokeRuntimeMethod(runtimeClass: Class[_], methodName: String): Unit = {
    val runtimeMethod = runtimeClass.getDeclaredMethod(methodName)
    var runtimeClsConstructor: java.lang.reflect.Constructor[_] = null
    if (!Modifier.isStatic(runtimeMethod.getModifiers)) {
      runtimeClsConstructor = runtimeClass.getDeclaredConstructor()
      runtimeClsConstructor.setAccessible(true)
    }
    println("Return Type =>" + runtimeMethod.getReturnType)
    println("Generic Return Type => " + runtimeMethod.getGenericReturnType)

    runtimeMethod.setAccessible(true)
    val runtimeObj = if (runtimeClsConstructor != null) runtimeClsConstructor.newInstance()
    else runtimeClsConstructor

    val runtimeFunction = runtimeMethod.invoke(runtimeObj).asInstanceOf[Function1[String, String]]
    println("output => " + runtimeFunction("test"))

  }
}

Here i want to generalize the function so that i don't need to write Function1. I am already getting return type i.e. Generic Return Type => scala.Function1. How can i use this return type in asInstanceOf directly instead of hard coding Function1 like runtimeMethod.invoke(runtimeObj).asInstanceOf[runtimeMethod.getGenericReturnType]





Aucun commentaire:

Enregistrer un commentaire