我读了一些关于Scala Reflection的文章。如。http://docs.scala-lang.org/overviews/reflection/overview.html
在我的例子中,我想看看给定的类名是否可以实例化。例如org.apache.spark.sql.catalyst.SqlLexical
我不能直接使用SqlLexical(在Spark 1.6中定义),因为运行时可能是Spark 2.0
如何检索给定String classname的类?
谢谢
有帮助:
$ 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
往后地协调地:
$ 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
不是严格的scala解决方案,但您可以尝试使用ClassLoader加载它。