如何确定是否`this`是一个类或对象的实例?(How to determine if `this`

2019-10-17 06:21发布

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

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

Answer 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
}


Answer 2:

这里有一个比较俗气的想法:

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


文章来源: How to determine if `this` is an instance of a class or an object?