如何在 Scala 中使用类型参数获取 Class 的 class 对象?

How do I get the class object of Class with type parameters in Scala?

我是 Scala 的新手,对 Java 生疏了,我在某些语义上犯了错误。我正在尝试获取 SequenceFileOutputFormat 的 class 对象。

其他堆栈溢出帖子说要简单地执行以下操作:

classOf[SequenceFileOutputFormat] 

产生错误:

class SequenceFileOutputFormat takes type parameters

好的,所以它需要参数类型,所以我执行以下操作:

classOf[SequenceFileOutputFormat[String, String]]

产生错误:

[error]  found   : Class[org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat[String,String]](classOf[org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat])
[error]  required: Class[_ <: org.apache.hadoop.mapred.OutputFormat[_, _]]

什么给了?如何获取需要类型参数的 class 的 class 对象?

使用 hadoop-mapreduce-client-core“3.0.0”,这里是:

import org.apache.hadoop.mapreduce.lib.output._

object HadoopQuestion_48818781 {
  def main(args: Array[String]): Unit = {
    val c = classOf[SequenceFileOutputFormat[_, _]]
    println("Class: " + c)
  }
}

打印:

Class: class org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat

解释:

尽管classOf[T]是在编译时处理的,但Class[T]本身是一个运行时构造,它对T的泛型类型参数一无所知。因此,您必须为 runtime-erased 类型参数添加下划线 _。这些下划线实际上只是 Scala 中 存在类型 的语法糖,但在这种特殊情况下,它们的作用类似于 Java.

中的通配符。