【问题标题】:Scala classOf for type parameter: how to call the function and how to restrict with upper type boundsScala classOf 用于类型参数:如何调用函数以及如何限制类型上限
【发布时间】:2011-08-02 07:47:57
【问题描述】:

我正在使用 Scala 中的 JAX-RS 并尝试将调用参数化:

val jc = JAXBContext.newInstance(classOf[MyClassName])

根据here 的答案,我一直在使用 ClassManifests,但有几件事我仍在苦苦挣扎。作为背景,我的 JAX-RS 表示都扩展了一个存根表示类:

class Representation {}

class ExampleRepresentation extends Representation { ... }

到目前为止,我已经使用 ClassManifest 定义了我的函数,如下所示:

def get[R: ClassManifest](representation: R): String = {
  val jc = JAXBContext.newInstance(classManifest[R].erasure)
  ...
}

我的第一个问题有点傻:如何调用这个函数?我不知道要为 R 类型和表示值传递给 get() 的内容(对原始问题的接受答案并不清楚)。我根据范例的评论尝试了隐式输入,但下面会产生编译错误:

get(PlatformRepresentation)

Compiling main sources... 
  not found: value PlatformRepresentation

我的第二个问题是:是否可以在 R 对象上应用上限类型?换句话说,我知道:

R <: Representation

有没有办法在 get() 的 ClassManifest 类型声明中限制 this?

非常感谢!

【问题讨论】:

  • 要调用它,只需将参数传递给get 即可推断类型。
  • 感谢范式-我已经更新了我的问题。我试图澄清我没有传递给 get() 的值,我只有一个类名可以传递。

标签: scala


【解决方案1】:

如果你没有参数,你需要抑制:

def get[R <: Representation: ClassManifest]: String = {
    val classManifest = implicitly[ClassManifest[R]] //to retrieve the class manifest
}

称呼它:

get[PlatformRepresentation]

类型在方括号之间。

【讨论】:

【解决方案2】:

关于你的第二个问题:是的,有办法做到这一点:

def get[R <: Representation: ClassManifest](representation: R): String

当您声明类型参数时,您可以包含一个带有&gt;: 的下限,一个带有&lt;: 的上限,以及您想要的尽可能多的上下文边界(带有:)和视图边界(带有&lt;%)需要。

【讨论】:

    【解决方案3】:

    一个例子:

    scala> def b[T <: String : ClassManifest] (t:T) = t + " " + classManifest[T].era
    sure;
    b: [T <: String](t: T)(implicit evidence$1: ClassManifest[T])java.lang.String
    
    scala> b("hello")
    res2: java.lang.String = hello class java.lang.String
    

    编辑 @paradigmatic 是对的,在你的情况下应该是

    scala> def c[T <: String : ClassManifest] = classManifest[T].erasure;
    c: [T <: String](implicit evidence$1: ClassManifest[T])java.lang.Class[_]
    
    scala> c[String];
    res4: java.lang.Class[_] = class java.lang.String
    

    【讨论】:

    • 感谢 paolo - 但我没有传递给 b 的值,我只有类名。换句话说,我需要 b(String) 工作而不是 b("string") (当然它不需要)。
    猜你喜欢
    • 2011-09-06
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2020-08-26
    相关资源
    最近更新 更多