def persist(serviceDStream: DStream[Any]): Unit = serviceDStream match {
case _: DStream[Service1] => println("it is a Service1")
case _: DStream[Service2] => println("it is a Service2")
case _ => println("who knows")
}
runtime type erasure
使用shapeless
更多信息shapeless-guide改进解决方案:
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.DStream
import shapeless.TypeCase
object Test {
def main(args: Array[String]): Unit = {
val spark = SparkSession
.builder
.getOrCreate()
case class Service1 (a: String)
case class Service2 (a: Int)
val Service1Typed = TypeCase[DStream[Service1]]
val Service2Typed = TypeCase[DStream[Service2]]
def persist(serviceDStream: DStream[Any]): Unit = serviceDStream match {
case Service1Typed => println("it is a Service1")
case Service2Typed => println("it is a Service2")
case _ => println("who knows")
}
}
}
您还可以使用import scala.reflect.ClassTag
更多信息:ClassTag 示例