如何判断`this`是一个类还是一个对象的实例?

时间:2012-09-24 19:49:11

标签: scala singleton instance

假设我有两个抽象类的后代:

object Child1 extends MyAbstrClass {
    ...
}
class Child2 extends MyAbstrClass {
}

现在我想确定(最好是在MyAbstrClass的构造函数中)创建的实例是一个对象还是由new创建的东西:

abstract class MyAbstrClass {
    {
        if (/* is this an object? */) {
            // do something
        } else {
            // no, a class instance, do something else
        }
    }
}

Scala中有可能出现这种情况吗?我的想法是将从类中下降的所有对象收集到一个集合中,但只收集对象,而不是由new创建的实例。

2 个答案:

答案 0 :(得分:1)

这是一个相当俗气的想法:

trait X {
  println("A singleton? " + getClass.getName.endsWith("$"))
}

object Y extends X
Y // objects are lazily initialised! this enforces it

class Z extends X
new Z

答案 1 :(得分:1)

类似的东西:

package objonly

/** There's nothing like a downvote to make you not want to help out on SO. */
abstract class AbsFoo {
  println(s"I'm a ${getClass}")
  if (isObj) {
    println("Object")
  } else {
    println("Mere Instance")
  }
  def isObj: Boolean = isObjReflectively

  def isObjDirty = getClass.getName.endsWith("$")

  import scala.reflect.runtime.{ currentMirror => cm }
  def isObjReflectively = cm.reflect(this).symbol.isModuleClass
}

object Foo1 extends AbsFoo

class Foo2 extends AbsFoo

object Test extends App {
  val foob = new Foo2
  val fooz = new AbsFoo { }
  val f = Foo1
}
相关问题