0
votes

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

2 Answers

1
votes

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
0
votes

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