How to determine if `this` is an instance of a class or an object?

Deadly 提交于 2019-12-11 09:38:40

问题


Suppose I have two descendants of an abstract class:

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

Now I'd like to determine (preferably in the constructor of MyAbstrClass) if the instance being created is an object or something created by new:

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

Is anything like that possible in Scala? My idea is to collect all objects that descend from a class into a collection, but only object, not instances created by new.


回答1:


Something like:

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
}



回答2:


Here's a rather cheesy idea:

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


来源:https://stackoverflow.com/questions/12571881/how-to-determine-if-this-is-an-instance-of-a-class-or-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!