一般获取 Scala 类型的清单

发布于 2024-12-28 10:34:09 字数 62 浏览 2 评论 0原文

有没有办法通用地获取 Scala 类型的清单?例如,如果我只有一个类引用可以使用,有没有办法获得其相应的清单?

Is there a way to generically obtain a Scala type's manifest? For example, if I only have a Class reference to work with, is there a way I can obtain its corresponding manifest?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青萝楚歌 2025-01-04 10:34:09

Scala 的内置 implicitly[T] 将为您提供 T 类型的隐式值(如果存在)。因此,隐式[Manifest[T]]将返回类型T的Manifest。

如果您有Class引用,则可以像这样获取该类的Manifest:

def manifestFor[T: Manifest](c: Class[T]) = implicitly[Manifest[T]]

class Foo
val x =  new Foo
manifestFor(x.getClass)
//scala.reflect.Manifest[_ <: Foo] = _ <: Foo

Manifest的类型为_ < ;: Foo 而不仅仅是 Foo,但它们是相等的。

implicitly[Manifest[Foo]] == manifestFor(x.getClass)
//Boolean = true

Scala's built-in implicitly[T] will get you an implicit value of type T (if one exists). So implicitly[Manifest[T]] will return a Manifest for type T.

If you have a Class reference, you can get the Manifest for the Class like this:

def manifestFor[T: Manifest](c: Class[T]) = implicitly[Manifest[T]]

class Foo
val x =  new Foo
manifestFor(x.getClass)
//scala.reflect.Manifest[_ <: Foo] = _ <: Foo

The Manifest's type is _ <: Foo instead of just Foo, but they are equal.

implicitly[Manifest[Foo]] == manifestFor(x.getClass)
//Boolean = true
坚持沉默 2025-01-04 10:34:09

嗯,我试图做一些类似的事情,但经过反思。我在编译时没有可用的类符号。我必须使用这段代码,从 scaladocs 来看并不是那么明显,在该点附近存在多种非显而易见和误导性的方法,因此它可能对其他人有用。

Manifest.classType(Class.forName(className))

Well, I was trying to do something similar, but reflectively. I had no class symbol at compile time available. I had to use this code, not so obvious from the scaladocs, whith multiple non-obvious and misleading methods present near that point, so that it would likely be useful to others out there.

Manifest.classType(Class.forName(className))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文