From Scala, I'm using a Java library that expects a class argument. Example:
def service: OAuthService = new ServiceBuilder()
.provider(classOf[RunApi])
RunApi is Java class.
I'd like to be able pass a variety of classes to provider though. I have a list of them in String format.
Example, if I know the RunApi in String format; e.g. "com.me.RunApi", how can construct the equivalent to above code?
Use forName
method:
scala> Class.forName("scala.collection.mutable.ArrayBuffer")
res0: java.lang.Class[_] = class scala.collection.mutable.ArrayBuffer
val yourInstance: ClassOrTrait = Class.forName("Package.ClassName").newInstance().asInstanceOf[ClassOrTrait]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With