I saw lots of websites about scala reflection library but none of them have a straightforward answer to instantiate an object of the class at runtime. For example, I have the following code:
trait HydraTargetTable {
val inputTables = Seq.empty[Int]
val tableType: String
val tableName: String
val schema: StructType
def className: String = this.getClass.toString
}
trait HydraIntermediateTable extends HydraTargetTable {
val tableType = "Intermediate"
def build(textRDD: RDD[String]): DataFrame = {
DataframeUtils.safeParseFromSchema(textRDD, schema)
}
}
class Table1 extends HydraIntermediateTable {
override val inputTables: Seq[Int] = Seq(1, 2)
override val tableName: String = ""
override val schema: StructType = new StructType()
}
At runtime, I want to be able to instantiate an object of Table1 given the class name as a String value. Here is my reflection code.
object ReflectionTestApp {
def tableBuilder(name: String): Intermediate = {
Class.forName("hearsay.hydra.dataflow.api." + name).newInstance()
.asInstanceOf[Intermediate]
}
def hydraTableBuilder(name: String): HydraTargetTable = {
val action = Class
.forName("hearsay.hydra.dataflow.api." + name).newInstance()
action.asInstanceOf[HydraTargetTable]
}
def main(args: Array[String]): Unit = {
hydraTableBuilder("Table1").inputTables.foreach(println)
}
}