mercredi 11 septembre 2019

Call scala method from object dynamically

I have a scala case class and object like below,

case class User(userId: Long, UserName: String, ts: Timestamp)

object User {

  def getRdd(rdd: RDD[JsValue], type : String): RDD[User] = {

    val rdd1: RDD[User] = rdd.map(doc => processEvent(doc))
      .filter(event => event._1.equals(rddType)).map(event => {
      User.get_class_obj(event)
    })
    rdd1
  } 

}

I want to call "getRdd" method of User Object from another object without creating instance of object/class. like below,

val object_name = "com.User"
val method_name = "getRdd"

I tried,

val no = Array(1, 2, 3, 4, 5,6,7,8,9,10)
val rdd = sc.parallelize(no)


Class.forName(object_name).getDeclaredMethod(method_name).invoke(rdd)

but fails with nosuchmethod error. I have gone through answers here but I don't want to create multiple instances every time. Is it possible to do it in one-liner.





Aucun commentaire:

Enregistrer un commentaire