0

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?

1 Answer 1

2

If you want to get the class by name, just go with your preferred of first two approaches.

ClassTags don't provide anything useful for this, and they aren't supposed to. In particular, ClassTag(someClass).runtimeClass which you do in 3) will always just return someClass.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah tried bunch of ways, ClassTag[T] does not seem to provide much value in this case. I might go with #2 (isAssignableFrom ) and throw my own exception in case of bad class-name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.