Scala classOf 用于类型参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6200253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala classOf for type parameter
提问by mericano1
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 创建一个用于对象更新的通用方法,但我无法获取类型参数的类。
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
需要类类型,但找到了 T
I know in java you can't do it but is this possible in scala at all?
我知道在 Java 中你不能这样做,但这在 Scala 中可能吗?
Thanks!
谢谢!
回答by Vasil Remeniuk
Due Manifestis deprecated(Since Scala 2.10.0) this is the updated answer -
由于清单被弃用(因为斯卡拉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 ClassTaginstead of ClassManifestand .runtimeClassinstead 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);
...
}
}
回答by akauppi
Vasil's and Maxim's answer helped me.
Vasil 和 Maxim 的回答帮助了我。
Personally, I prefer the syntax where implicitis used for adding such parameters (the presented : ClassTagis shorthand for it. So here, in case someone else also sees this to be a better way:
就个人而言,我更喜欢 whereimplicit用于添加此类参数的语法(呈现的: 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.
免责声明:我没有编译上面的代码,但我自己的类似代码是这样工作的。

