简体   繁体   English

Scala classOf 用于类型参数

[英]Scala classOf for type parameter

I am trying to create a generic method for object updates using scala / java but I can't get the class for a type parameter.我正在尝试使用 scala / java 为 object 更新创建通用方法,但我无法获得 aCABCB4 类型参数的 ZA2F222ED4F8EBC26614 参数。

Here is my code:这是我的代码:

object WorkUnitController extends Controller {     
 def updateObject[T](toUpdate: T, body: JsonObject){
  val source = gson.fromJson(body, classOf[T]);
  ...
 }
}

The error i get is我得到的错误是

class type required but T found需要 class 类型但找到 T

I know in java you can't do it but is this possible in scala at all?我知道在 java 中你不能这样做,但在 scala 中这可能吗?

Thanks!谢谢!

Due Manifest is deprecated (Since Scala 2.10.0) this is the updated answer -不推荐使用到期清单(自 Scala 2.10.0 起)这是更新的答案 -

import scala.reflect.ClassTag
import scala.reflect._

object WorkUnitController extends Controller {
  def updateObject[T: ClassTag](toUpdate: T, body: JsonObject){
    val source = gson.fromJson(body, classTag[T].runtimeClass)
    ???
  }
}

You should use ClassTag instead of ClassManifest and .runtimeClass instead of .erasure您应该使用ClassTag而不是ClassManifest.runtimeClass而不是.erasure

Original answer - Yes, you can do that using manifests:原始答案 -是的,您可以使用清单来做到这一点:

object WorkUnitController extends Controller {     
 def updateObject[T: ClassManifest](toUpdate: T, body: JsonObject){
  val source = gson.fromJson(body, classManifest[T].erasure);
  ...
 }
}

Vasil's and Maxim's answer helped me.瓦西尔和马克西姆的回答帮助了我。

Personally, I prefer the syntax where implicit is used for adding such parameters (the presented : ClassTag is shorthand for it. So here, in case someone else also sees this to be a better way:就个人而言,我更喜欢使用implicit添加此类参数的语法(呈现的: ClassTag是它的简写。所以在这里,如果其他人也认为这是更好的方法:

import scala.reflect.ClassTag

object WorkUnitController extends Controller {
  def updateObject[T](toUpdate: T, body: JsonObject)(implicit tag: ClassTag[T]){
    val source = gson.fromJson(body, tag.runtimeClass)
    ???
  }
}

Disclaimer: I did not compile the above, but my own similar code works this way.免责声明:我没有编译上述内容,但我自己的类似代码以这种方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM