Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - get class from a string

Tags:

scala

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?

like image 988
Todd M Avatar asked Feb 13 '12 22:02

Todd M


2 Answers

Use forName method:

scala> Class.forName("scala.collection.mutable.ArrayBuffer")
res0: java.lang.Class[_] = class scala.collection.mutable.ArrayBuffer
like image 67
om-nom-nom Avatar answered Oct 16 '22 02:10

om-nom-nom


val yourInstance: ClassOrTrait = Class.forName("Package.ClassName").newInstance().asInstanceOf[ClassOrTrait]

like image 1
Bday Avatar answered Oct 16 '22 02:10

Bday