I am trying to get the instance of runtimeClass from Class[_] in scala. This is going to happen before I create my jar app.
1) Here's my simple example using old java way where I'm trying to get instance of StringBuilder. (In my actual codebase it would be some classes extending a trait EventProcessor)
scala> val clazz = Class.forName("scala.collection.mutable.StringBuilder")
clazz: Class[_] = class scala.collection.mutable.StringBuilder
scala> clazz.newInstance().asInstanceOf[StringBuilder].append("updating stuffs")
res1: StringBuilder = updating stuffs
2) Another approach I can use is isAssisgnableFrom,
scala> val clazz = Class.forName("scala.collection.mutable.StringBuilder")
clazz: Class[_] = class scala.collection.mutable.StringBuilder
scala> if(clazz.isAssignableFrom(classOf[StringBuilder])) clazz.newInstance.asInstanceOf[StringBuilder].append("some default data")
else throw new Exception(s"$clazz is not what i want")
res2: StringBuilder = some default data
3) But I am attempting to get the runtimeClass instead and get the instance if the right type if not fail fast.
I found hundreds of posts on scala ClassTag[_] but could not make it work how I want to. Maybe asInstanceOf[T] is best approach for what I want.
One example using ClassTag, where I still have to do asInstanceOf[T]. If so what is the advantage over old asInstanceOf[T].
scala> ClassTag[StringBuilder](Class.forName("scala.collection.mutable.StringBuilder"))
res2: scala.reflect.ClassTag[StringBuilder] = scala.collection.mutable.StringBuilder
scala> res2.runtimeClass.newInstance.asInstanceOf[StringBuilder].append("update state")
res3: StringBuilder = update state
Also misleading thing above is that I can provide wrong Type to ClassTag as below,
scala> ClassTag[Int](Class.forName("scala.collection.mutable.StringBuilder")).runtimeClass
res4: Class[_] = class scala.collection.mutable.StringBuilder
My question is what is a recommended approach to get the instance of runtimeClass in scala?