AKR
AKR

Reputation: 531

Scala: generate class from a string

I want to dynamically create a Class from a String.

The String has the exact name of the Class (by the way is a Java class)

For example

val classString = "gui.MainFrame"

I create the class with

val mainClass: Class[_] = Class.forName(classString)

Scala founds the class, but if i want to use this class for example with

AppExecutor.executeNoBlock(classOf[mainClass])

Scala tells me that type mainClass cannot be found.

If i use it in that way

AppExecutor.executeNoBlock(mainClass.asInstanceOf)

it says that java.lang.Class cannot be cast to scala.runtime.Nothing$ So how can i use this class now?

Upvotes: 1

Views: 743

Answers (1)

mikołak
mikołak

Reputation: 9705

"You're holding it wrong."

classOf accepts a type parameter and returns a Class object. You can't pass a Class object as a type parameter, hence the error.

Also, you already have your Class object in mainClass. If you want to necessarily use classOf, you can do this:

val mainClass = classOf[gui.MainFrame]

instead. But otherwise you should stick to your previous approach, i.e.:

val mainClass = Class.forName(classString)

If the code you're trying to use is org.jemmy.fx.AppExecutor, you can just invoke it directly with mainClass:

AppExecutor.executeNoBlock(mainClass.asInstanceOf[Class[_ <: javafx.application.Application]])

Since the method apparently has a qualified type parameter (i.e. not a normal wildcard Class[_], or Class<?> in Java notation).

Upvotes: 2

Related Questions