[英]Scala reflection: How to construct object and run its methods given 'String-type' class name and method name?
[英]Scala Reflection: how to get class given String name of the class
我讀了一些有關Scala反射的文章。 例如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解決方案,但是您可以嘗試使用ClassLoader.loadClass加載它,然后獲取構造函數並將其調用為實例。
有幫助:
$ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.