gpt4 book ai didi

scala - 在 Scala 中动态创建类,我应该使用解释器吗?

转载 作者:行者123 更新时间:2023-12-04 01:07:48 25 4
gpt4 key购买 nike

我想在运行时在 Scala 中创建一个类。现在,只考虑一个简单的案例,我想制作一个具有某些属性的 java bean 的等价物,我只在运行时知道这些属性。

如何创建 Scala 类?如果有一种方法可以编译它并在运行时加载它,我愿意从 Scala 源文件创建它,我可能想要,因为有时我想将一些复杂的函数添加到类中。我该怎么做?

我担心我读到的 scala 解释器正在沙盒它加载的解释代码,以便它对托管解释器的一般应用程序不可用?如果是这种情况,那么我将无法使用动态加载的 scala 类。

无论如何,问题是,如何在运行时动态创建 Scala 类并在我的应用程序中使用它,最好的情况是在运行时从 Scala 源文件加载它,例如 interpreterSource("file.scala")并将其加载到我当前的运行时中,第二好的情况是通过调用方法进行一些创建,即。 createClass(...)在运行时创建它。

谢谢,菲尔

最佳答案

没有足够的信息来了解最佳答案,但请记住您是在 JVM 上运行的,因此任何对 Java 有效的技术或字节码工程库在这里也应该有效。

您可能会使用数百种技术,但最佳选择完全取决于您的具体用例,因为很多都不是通用的。不过,这里有一些想法:

  • 对于一个简单的bean,你也可以
    只需使用 map ,或查看
    来自 apache commons 的 DynaBean 类。
  • 对于更高级的行为,你可以
    显式调用编译器并
    然后获取生成的 .class 文件
    通过类加载器(这主要是
    JSP 是如何做到的)
  • 解析器和自定义 DSL 非常适合
    一些案例。 bean shell 也一样
    脚本。

  • 在此处查看 ScalaDays 视频: http://days2010.scala-lang.org/node/138/146
    它演示了如何使用 Scala 作为符合 JSR-223 的脚本语言。
    这应该涵盖您希望在运行时评估 Scala 的大多数场景。

    您还需要查看此处的电子邮件主题: http://scala-programming-language.1934581.n4.nabble.com/Compiler-API-td1992165.html#a1992165

    这包含以下示例代码:
    // We currently call the compiler directly 
    // To reduce coupling, we could instead use ant and the scalac ant task

    import scala.tools.nsc.{Global, Settings}
    import scala.tools.nsc.reporters.ConsoleReporter
    {
    // called in the event of a compilation error
    def error(message: String): Nothing = ...

    val settings = new Settings(error)
    settings.outdir.value = classesDir.getPath
    settings.deprecation.value = true // enable detailed deprecation warnings
    settings.unchecked.value = true // enable detailed unchecked warnings

    val reporter = new ConsoleReporter(settings)

    val compiler = new Global(settings, reporter)
    (new compiler.Run).compile(filenames)

    reporter.printSummary
    if (reporter.hasErrors || reporter.WARNING.count > 0)
    {
    ...
    }
    }


    val mainMethod: Method = {
    val urls = Array[URL]( classesDir.toURL )

    val loader = new URLClassLoader(urls)

    try {
    val clazz: Class = loader.loadClass(...)

    val method: Method = clazz.getMethod("main", Array[Class]( classOf[Array[String]] ))
    if (Modifier.isStatic(method.getModifiers)) {
    method
    } else {
    ...
    }
    } catch {
    case cnf: ClassNotFoundException => ...
    case nsm: NoSuchMethodException => ...
    }
    }

    mainMethod.invoke(null, Array[Object]( args ))

    关于scala - 在 Scala 中动态创建类,我应该使用解释器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2752206/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com