Create class object dynamically / reflection


#1

we are creating framework based on Scala .
where accepting runtime value from user and based on which creating object of an class .

Scenario 1: where we are not returning array of object is working

calling method
val scnHttpconf = Class.forName(“package.compDB.Scripts.”+script1).newInstance.asInstanceOf[{ def call( env:String): (ScenarioBuilder,HttpProtocolBuilder) }]
val (scn, httpconf)=scnHttpconf.call(env)

method definition

def call(env:String):(ScenarioBuilder,HttpProtocolBuilder)=
{
this.env=env
// do somethingand return
(callScenario,httpConf) // last stmt considered as return result

}

Scenario 2: where we are returning array of object is not working

calling method

// in this line itself we are getting error . : java.lang.reflect.Array does not take type parameters
val scnHttpconf = Class.forName(“package.compDB.Scripts.”+script1).newInstance.asInstanceOf[{ def call( env:String): (Array[ScenarioBuilder],HttpProtocolBuilder) }]

   val (scn, httpconf)=scnHttpconf.call(env)

method definition

def call(env:String):(Array[ScenarioBuilder],HttpProtocolBuilder)=
{
this.env=env
// do somethingand , callScenario is array object of ScenarioBuilder
(callScenario,httpConf) // last stmt considered as return result

}

#2

Based on the compilation error you’re getting, I would guess you have import java.lang.reflect._ somewhere in your code. Which means that scala.Array gets shadowed by java.lang.reflect.Array, resulting in the error you are seeing.
My preferred fix would be excluding Array from the import:

import java.lang.reflect.{Array => _, _}

Or if you are actually using java.lang.reflect.Array, rename it to something else:

import java.lang.reflect.{Array => ArrayReflect, _}

#3

Bang on … thank you jasper for your time . it has fixed our issue .