Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取Scala中泛型类型的类名_Scala - Fatal编程技术网

获取Scala中泛型类型的类名

获取Scala中泛型类型的类名,scala,Scala,我有一个函数readObjectFromFile,具有泛型类型T。我如何知道类型名称 import scala.reflect.runtime.universe.{typeOf, TypeTag} def name[T: TypeTag] = typeOf[T].typeSymbol.name.toString name[Int] res5: String = Int import java.io._ def readObjectFromFile[T](file: File): T =

我有一个函数
readObjectFromFile
,具有泛型类型T。我如何知道类型名称

import scala.reflect.runtime.universe.{typeOf, TypeTag}

def name[T: TypeTag] = typeOf[T].typeSymbol.name.toString

name[Int]
res5: String = Int

import java.io._

def readObjectFromFile[T](file: File): T = {
  val typeName = name[T]
  println(s"read ${typeName} from file $file")
  val ois = new ObjectInputStream(new FileInputStream(file))
  val v = ois.readObject.asInstanceOf[T]
  ois.close()
  v
}

cmd19.sc:2: No TypeTag available for T
  val typeName = name[T]

ps:我知道我可以使用v.getClass.getName,但这将在读取对象后完成。我想在读取对象之前打印此信息。

readObjectFromFile
还需要隐式的
TypeTag
,以便
name
能够解析它

import scala.reflect.runtime.universe.{typeOf, TypeTag}
import java.io._

def name[T: TypeTag] = typeOf[T].typeSymbol.name.toString

def readObjectFromFile[T: TypeTag](file: File): T = {
  val typeName = name[T]
  println(s"read ${typeName} from file $file")
  val ois = new ObjectInputStream(new FileInputStream(file))
  val v = ois.readObject.asInstanceOf[T]
  ois.close()
  v
}

您通常希望在
中包装
ois.readObject
,然后在
中最后放入
close
,这样您就不会在失败时使文件未关闭。或者更好地使用scala中的资源分配;这不是生产代码;这只是一个最小、完整且可验证的示例: