1

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?

1 Answer 1

2

"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).

Sign up to request clarification or add additional context in comments.

7 Comments

Yes you are right, i want to use the AppExecutor from Jemmy, and i know that i can call it directly with "mainClass", but the problem is, that the value of "mainClass" should not be the same every time. It should be variable, so that a user can enter another Class that is startet with AppExecutor. So i cannot use val mainClass = classOf[gui.MainFrame], because it would not be variable.
@AKR : like I said, you can still use Class.forName(classString) if that's the case, the problem was in how you invoked executeNoBlock().
I tried it that way: "val mainClass = Class.forName(mainClassString)" and then "AppExecutor.executeNoBlock(mainClass)" but this leads to the error message "- overloaded method value executeNoBlock with alternatives: (x$1: Class[_ <: javafx.application.Application],x$2: <repeated...>[String])Unit <and> (x$1: Class[_ <: javafx.application.Application])Unit cannot be applied to (Class[?0(in value <local $anon>)])"
@AKR. That's another story. Not sure if I got the cast correctly, but see my edit.
No problem. Thank you for your advice to accept the answer, i'm new to stackoverflow, so i haven't got all the features of this wonderful site now. ;)
|

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.