本文介绍了强制初始化 Scala 单例对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发基于 Dozer 的自动映射框架.我不会详细说明,因为它与问题无关,但总的来说,它应该允许从 A 类轻松转换到 B 类.我想注册一个类的伴随对象的投影.

I'm working on an automatic mapping framework built on top of Dozer. I won't go into specifics as it's not relevant to the question but in general it's supposed to allow easy transformation from class A to class B. I'd like to register the projections from a class's companion object.

下面是我希望它如何工作的(简化)示例,以及确保投影正确注册的规格测试.

Below is a (simplified) example of how I want this to work, and a Specs test that assures that the projection is being registered properly.

不幸的是,这不起作用.据我所知,这是因为没有初始化 A 伴随对象.事实上,如果我在 A 对象上调用任何方法(如注释掉的 hashCode 调用,投影被正确注册.

Unfortunately, this doesn't work. From what I can gather, this is because nothing initializes the A companion object. And indeed, if I call any method on the A object (like the commented-out hashCode call, the projection is being registered correctly.

我的问题是 - 如何在 JVM 启动后立即自动初始化 A 对象?如有必要,我不介意扩展 Trait 或其他东西.

My question is - how can I cause the A object to be initialized automatically, as soon as the JVM starts? I don't mind extending a Trait or something, if necessary.

谢谢.

class A {
  var data: String = _
}

class B {
  var data: String = _
}

object A {
  projekt[A].to[B]

}

"dozer projektor" should {
  "transform a simple bean" in {
//    A.hashCode
      val a = new A
      a.data = "text"
      val b = a.-->[B]

      b.data must_== a.data
  }
}

推荐答案

最后这样做了:

trait ProjektionAware with DelayedInit
{
  private val initCode = new ListBuffer[() => Unit]

  override def delayedInit(body: => Unit)
  {
    initCode += (() => body)
  }


  def registerProjektions()
  {
    for (proc <- initCode) proc()
  }
}

object A extends ProjektionAware {
  projekt[A].to[B]

}

现在我可以使用类路径扫描库在应用程序引导程序上初始化 ProjektionAware 的所有实例.不理想,但对我有用.

Now I can use a classpath scanning library to initialize all instances of ProjektionAware on application bootstrap. Not ideal, but works for me.

这篇关于强制初始化 Scala 单例对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:53