在 Scala 中使用 ClassManifest 从 Any 转换值
我有一个值的 List[Any]
和相应的 ClassManifest[_]
列表,用于存储值的原始类型。如何将列表中的某些值转换回其原始类型?
defcast[T](x: Any, mf: ClassManifest[T]): T = x.asInstanceOf[T]
不起作用。
谢谢您的回答。
I've got a List[Any]
of values and a list of corresponding ClassManifest[_]
s, storing values' original types. How do i cast some value from list back to it's original type?
def cast[T](x: Any, mf: ClassManifest[T]): T = x.asInstanceOf[T]
doesn't work.
Thank You for your answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不可能的,因为
cast
的返回类型将始终被视为T
所限制的最高通用超类型。无法在编译时使其变得更加具体。如果您尝试构建不同类型的强类型集合,那么您真正想要的是 HList:
http://jnordenberg.blogspot.com/2008/09/hlist-in-scala-revisited-or-scala.html
That can't ever possibly work, as the return type of
cast
will always be taken as the highest common supertype of whateverT
is restricted to. There's no way it can be made any more specific at compile time.If you're trying to build a strongly-typed collection of disparate types, then what you really want is an HList:
http://jnordenberg.blogspot.com/2008/09/hlist-in-scala-revisited-or-scala.html
在 Java/Scala 中使用
Class
实例来转换对象的方法是使用Class.cast
方法。所以你可能认为你可以这样做:但这是行不通的,因为
mf.erasure
是一个Class[_]
(或一个Class
in Java),因此强制转换毫无意义(即不提供额外信息)。 (当然)这是使用非具体化泛型的缺点之一。The way to use a
Class
instance in Java/Scala to cast an object is to use theClass.cast
method. So you may think that you could do:But this will not work, because
mf.erasure
is aClass[_]
(or aClass<?>
in Java), so the cast is meaningless (i.e. offers no extra information). This is (of course) one of the drawbacks in using non-reified generics.