简体   繁体   中英

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?

"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, ie:

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 (ie not a normal wildcard Class[_] , or Class<?> in Java notation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM