问题描述
如果我有一个对象的实例,有没有办法检查我是否有一个单例对象而不是一个类的实例?有什么方法可以做到这一点吗?可能是一些反射API?我知道一个区别是单例对象的类名以 $
结尾,但这不是一种严格的方式.
If I have an instance of an object, is there a way to check if I have a singleton object rather than an instance of a class?Is there any method can do this? May be some reflection API?I know that one difference is that the class name of a singleton object ends with a $
, but this is not a strict way.
推荐答案
是的,使用文档很少的 scala.Singleton
类型:
Yep, using the little-documented scala.Singleton
type:
def isSingleton[A](a: A)(implicit ev: A <:< Singleton = null) =
Option(ev).isDefined
然后:
scala> val X = new Foo(10)
X: Foo = Foo@3d5c818f
scala> object Y extends Foo(11)
defined object Y
scala> isSingleton(X)
res0: Boolean = false
scala> isSingleton(Y)
res1: Boolean = true
我的 isSingleton
方法只是一个演示,它提供了一个运行时布尔值,该值告诉您表达式是否静态类型为单例类型,但您也可以使用 Singleton
作为编译时类型是单例类型的证据.
My isSingleton
method is just a demonstration that provides a runtime boolean value that tells you whether or not an expression is statically typed as a singleton type, but you can also use Singleton
as evidence at compile time that a type is a singleton type.
这篇关于在 Scala 中,有没有办法检查实例是否是单例对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!