[英]Scala classOf for type parameter
我正在嘗試使用 scala / java 為 object 更新創建通用方法,但我無法獲得 aCABCB4 類型參數的 ZA2F222ED4F8EBC26614 參數。
這是我的代碼:
object WorkUnitController extends Controller {
def updateObject[T](toUpdate: T, body: JsonObject){
val source = gson.fromJson(body, classOf[T]);
...
}
}
我得到的錯誤是
需要 class 類型但找到 T
我知道在 java 中你不能這樣做,但在 scala 中這可能嗎?
謝謝!
不推薦使用到期清單(自 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)
???
}
}
您應該使用ClassTag
而不是ClassManifest
和.runtimeClass
而不是.erasure
原始答案 -是的,您可以使用清單來做到這一點:
object WorkUnitController extends Controller {
def updateObject[T: ClassManifest](toUpdate: T, body: JsonObject){
val source = gson.fromJson(body, classManifest[T].erasure);
...
}
}
瓦西爾和馬克西姆的回答幫助了我。
就個人而言,我更喜歡使用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)
???
}
}
免責聲明:我沒有編譯上述內容,但我自己的類似代碼以這種方式工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.