12

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?

2 Answers 2

19

Use forName method:

scala> Class.forName("scala.collection.mutable.ArrayBuffer")
res0: java.lang.Class[_] = class scala.collection.mutable.ArrayBuffer
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, thought it was going to work, but: [error] (org.scribe.builder.api.Api)org.scribe.builder.ServiceBuilder <and> [error] (java.lang.Class[_ <: org.scribe.builder.api.Api])org.scribe.builder.ServiceBuilder [error] cannot be applied to (java.lang.Class[?0(in method service)]) [error] .provider(Class.forName("com.me.RunApi")) [error] ^ [error] one error found
Just cast it to the required type: Class.forName("com.me.RunApi").asInstanceOf[Class[_ <: org.scribe.builder.api.Api]].
Thanks. I tried that as well as Class.forName("com.me.RunApi").asInstanceOf(Api), but: java.lang.Class cannot be cast to org.scribe.builder.api.Api. RunApi extends an abstract parent class which implements Api interface.
2

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

Comments

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.