How to determine if `this` is an instance of a class or an object?
假设我有两个抽象类的后代:
现在,我想确定(最好是在
1 2 3 4 5 6 7 8 9 |
斯卡拉有这种可能吗?我的想法是将所有从一个类下降到一个集合中的对象收集起来,但只收集对象,而不收集由
类似:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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 } |
这里有一个相当俗气的想法:
1 2 3 4 5 6 7 8 9 |