如何确定"this"是类的实例还是对象的实例? [英] How to determine if `this` is an instance of a class or an object?
本文介绍了如何确定"this"是类的实例还是对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个抽象类的两个后代:
Suppose I have two descendants of an abstract class:
object Child1 extends MyAbstrClass {
...
}
class Child2 extends MyAbstrClass {
}
现在,我想确定(最好在MyAbstrClass
的构造函数中)正在创建的实例是对象还是new
创建的对象:
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
}
}
}
在Scala中有可能发生这种情况吗?我的想法是将所有从类派生到集合中的对象收集起来,但仅收集对象,而不收集由new
创建的实例.
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
.
推荐答案
类似的东西:
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
}
这篇关于如何确定"this"是类的实例还是对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文