【问题标题】:How can I produce TypeInformation from generic type in scala如何从 scala 中的泛型类型生成 TypeInformation
【发布时间】:2019-05-13 10:03:39
【问题描述】:
我正在尝试为具有泛型类型的类扩展 DeserializationSchema
class Foo[T] extends DeserializationSchema[T] {
...
override def getProducedType: TypeInformation[T] = TypeInformation.of(classOf[T])
}
但我得到了
需要类类型,但发现 T 覆盖了 def getProducedType:
TypeInformation[T] = TypeInformation.of(classOf[T])
任何想法
【问题讨论】:
标签:
scala
apache-flink
flink-streaming
【解决方案1】:
根据documentation
对于泛型类型,您需要“捕获”泛型类型信息
通过 TypeHint:
所以你可以让它像这样编译
class Foo[T] extends DeserializationSchema[T] {
...
override def getProducedType: TypeInformation[T] = TypeInformation.of(new TypeHint[T]{})
}
【解决方案2】:
除了从T 派生classOf,您还可以要求隐式TypeInformation[T] 作为Foo 声明的一部分:
class Foo[T](implicit typeInformation: TypeInformation[T]) extends DeserializationSchema[T] {
override def getProducedType: TypeInformation[T] = typeInformation
override def deserialize(message: Array[Byte]): T = ???
override def isEndOfStream(nextElement: T): Boolean = ???
}