0

I read a few posts on Scala Reflection. e.g. http://docs.scala-lang.org/overviews/reflection/overview.html

In my case, I want to see if given class name can be instantiated. e.g. org.apache.spark.sql.catalyst.SqlLexical

I cannot directly use SqlLexical (defined in Spark 1.6) because the runtime may be Spark 2.0

How can I retrieve the class given the String classname ?

Thanks

2 Answers 2

1

There's help:

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.

scala> import scala.reflect.internal.util.ScalaClassLoader
import scala.reflect.internal.util.ScalaClassLoader

scala> ScalaClassLoader(getClass.getClassLoader).tryToLoadClass("scala.Option")
res0: Option[Class[Nothing]] = Some(class scala.Option)

scala> ScalaClassLoader(getClass.getClassLoader).create("scala.UninitializedError")
res1: AnyRef = scala.UninitializedError: uninitialized value

Backwardly compatibly:

$ scala210
Welcome to Scala version 2.10.5 (OpenJDK 64-Bit Server VM, Java 1.7.0_95).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.tools.nsc.util.ScalaClassLoader
import scala.tools.nsc.util.ScalaClassLoader

scala> ScalaClassLoader(getClass.getClassLoader).create("scala.UninitializedError")
res0: AnyRef = scala.UninitializedError: uninitialized value

scala> 

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.

scala> import scala.tools.nsc.util.ScalaClassLoader
import scala.tools.nsc.util.ScalaClassLoader

scala> ScalaClassLoader(getClass.getClassLoader).create("scala.UninitializedError")
warning: there was one deprecation warning; re-run with -deprecation for details
res0: AnyRef = scala.UninitializedError: uninitialized value
Sign up to request clarification or add additional context in comments.

3 Comments

scala> import scala.reflect.internal.util.ScalaClassLoader <console>:7: error: object ScalaClassLoader is not a member of package scala.reflect.internal.util import scala.reflect.internal.util.ScalaClassLoader ^
The solution I am looking for has to work for both Scala 2.10 and 2.11
They moved classes around because of how the reflection library is structured. Such is history, such is FOSS.
0

Not strictly scala solution, but you can try to load it with ClassLoader.loadClass and then get constructors and call them to an instance.

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.