加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

斯卡拉反射

发布时间:2020-12-16 09:24:18 所属栏目:安全 来源:网络整理
导读:我想创建一个hashmap来存储参数名称及其值.然而,参数具有不同的类型.我可以使用HashMap [String,Any],但我不知道它们以后是哪种类型.无论如何我有可以恢复类型信息吗?或者有更好的存储方式吗? 解决方法 您想要访问静态类型信息还是动态类型信息?如果您使
我想创建一个hashmap来存储参数名称及其值.然而,参数具有不同的类型.我可以使用HashMap [String,Any],但我不知道它们以后是哪种类型.无论如何我有可以恢复类型信息吗?或者有更好的存储方式吗?

解决方法

您想要访问静态类型信息还是动态类型信息?如果您使用前者,则可以使用键入的键.这些方面的东西应该有效:

final class Key[T]

object Registry {
   private var backingMap: Map[Key[_],_] = Map.empty

   def put[T](k: Key[T],v: T) = backingMap += (k -> v)

   def get[T](k: Key[T]): Option[T] = backingMap get k map (_.asInstanceOf[T])
}

scala> val strKey = new Key[String] 
strKey: Key[String] = Key@31028a

scala> val intKey = new Key[Int]
intKey: Key[Int] = Key@7ae77ca4

scala> Registry.put(strKey,"asdf")

scala> Registry.get(strKey)
res0: Option[String] = Some(asdf)

scala> Registry.put(intKey,"asdf")
<console>:10: error: type mismatch;
 found   : Key[Int]
 required: Key[Any]
       Registry.put(intKey,"asdf")

或者,您可以使用无类型键并使用清单将类型信息存储在Map中(如Daniel suggested):

class Registry[K] {
   import scala.reflect.Manifest

   private var _map= Map.empty[K,(Manifest[_],Any)] 

   def put[T](key: K,item: T)(implicit m: Manifest[T]) {
      _map += (key -> (m,item))
   }

   def get[T](key:K)(implicit m : Manifest[T]): Option[T] = {
      for ((om,v) <- _map get key if om <:< m) 
         yield v.asInstanceOf[T]
   }
}

后一种方法的优点是您可以将任何东西用作键,而不必传递原始类型的键对象.但是,它的缺点是,在调用get方法时必须指定值类型.如果你指定了错误的类型,你将获得None,就好像密钥根本不在注册表中一样,而对于键入的键,你可以保证获得与密钥相关的任何值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读