jeudi 8 novembre 2018

Dynamic instantiation of Objects in Scala with arguments- asInstanceOf is not accepting parameter

I need to dynamically instantiate an Object in Scala. The class name is passed as a parameter to the main method. The actual class which has all methods is imported from another package

I referred solutions in below links

instantiate object with reflection using constructor arguments Scala: How do I dynamically instantiate an object and invoke a method using reflection?

My problems is I am not able pass the class name parameter to asInstanceOf. Below is the code.

import com.xxx.xxx.warehouse.sbi
val classParam = "sbi" //to make it easy, i hardcoded the value.
val constructor = Class.forName(classParam).getConstructors()(0)
val args = Array[AnyRef](String,String)
val instance1 
=constructor.newInstance(args:_*).asInstanceOf[classParam]

Last line in above code throws error classParam cannot be resolved. asInstanceOf would need aparameter of type T. My class "sbi" has so many methods .But in this case, how do I solve this. There are multiple classes similar to "sbi"





Aucun commentaire:

Enregistrer un commentaire