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"
What I am trying to solve:
I have 500 case classes to be imported from com.xxx.xxx.warehouse package. Let us name them sbi1, sbi2, sbi3...sbi500. All of those classes extend another class which has multiple methods. There is a method "getLatestVesrion" which finds latest version of the S3 file based on the class name. Each case class takes a S3 file as input
I need to fetch the latest version of each S3 file for all 500 data sets in S3 using above classes. Instead of calling each class explicitly,I want to invoke those classes dynamically as per the need. If I invoke them explicitly, I need to write 2 lines of code for each class. So, I would be passing the class name sbi1, sbi2,sbi3 ..sbi500 during runtime. Based on the classname, latest version needs to be fetched.
So technically, given a string for class name, how can I access methods in that class name?