Scala Reflection:如何获取类给定类的String名称

时间:2016-10-07 22:10:36

标签: scala reflection

我读了几篇关于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?

的情况下检索类

由于

2 个答案:

答案 0 :(得分:0)

不是严格的scala解决方案,但您可以尝试使用ClassLoader.loadClass加载它,然后获取构造函数并将它们调用到实例。

答案 1 :(得分:0)

有帮助:

$ 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