Scala classOf 用于类型参数 [英] Scala classOf for type parameter

查看:43
本文介绍了Scala classOf 用于类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 scala/java 创建用于对象更新的通用方法,但我无法获取类型参数的类.

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.

这是我的代码:

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

我得到的错误是

需要类类型但找到了 T

class type required but T found

我知道在 Java 中你不能这样做,但在 Scala 中这可能吗?

I know in java you can't do it but is this possible in scala at all?

谢谢!

推荐答案

Due Manifest弃用(自 Scala 2.10.0 起)这是更新的答案 - >

Due Manifest is deprecated (Since Scala 2.10.0) this is the updated answer -

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)
    ???
  }
}

你应该使用 ClassTag 而不是 ClassManifest.runtimeClass 而不是 .erasure

You should use ClassTag instead of ClassManifest and .runtimeClass instead of .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);
  ...
 }
}

这篇关于Scala classOf 用于类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆