【发布时间】:2016-11-16 02:07:10
【问题描述】:
当我只有类时,是否可以在 Scala 中获取对象的单例实例?考虑
object A {}
def getSingletonInstance[T](x: Class[T]): Option[T] = {
// output the singleton, if x is a singleton class i.e. defined by an object
// is this possible?
}
getSingletonInstance(A.getClass) // --> should return Some[A]
【问题讨论】:
-
仅适用于运行时反射。
-
是的,当然,但是运行时反射中是否有足够的信息?我该怎么做?
-
为什么不
def getSingletonInstance[T](x: Class[T]): Option[T]? -
相应地更新了问题。运行时这应该是相同的,因为我认为类型擦除,所以在解决方案中我们现在可能需要一个
asInstanceOf
标签: scala