通过反射判断类型是否为单例 [英] Determine whether type is singleton via reflection

查看:65
本文介绍了通过反射判断类型是否为单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何判断一个类型是否是单例?

How can I find out whether a type is a singleton or not?

case object Foo
case class Bar(i: Int)

def isSingleton[A](implicit t: reflect.ClassTag[A]): Boolean = ???

assert( isSingleton[Foo.type])
assert(!isSingleton[Bar     ])

推荐答案

Do you need a ClassTag (<:<ClassTag)?如果没有,那么它的工作方式如下:

Do you need a ClassTag (<:< is deprecated in ClassTag)? If not, then it works this way:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> def isSingleton[A : TypeTag] = typeOf[A] <:< typeOf[Singleton]
isSingleton: [A](implicit evidence$1: reflect.runtime.universe.TypeTag[A])Boolean

scala> isSingleton[Foo.type]
res5: Boolean = true

scala> isSingleton[Bar]
res6: Boolean = false

这篇关于通过反射判断类型是否为单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆