scala - 确定 Scala 类中 Option 字段的类型
问题描述
问题
你如何确定一个类的每个字段的类型?
给定以下案例类:
case class GenericCaseClass(
a: Boolean,
b: Byte,
c: Short,
d: Int,
e: Long,
f: Float,
g: Double,
h: Char,
i: String,
j: Option[Boolean],
k: Option[Byte],
l: Option[Short],
m: Option[Int],
n: Option[Long],
o: Option[Float],
p: Option[Double],
q: Option[Char],
r: Option[String]
)
初步尝试
import java.lang.reflect.{Field, ParameterizedType}
def printType(field: Field): Unit = {
val scalaClass = field.getType
if (scalaClass == classOf[Boolean]) {
println("Boolean")
} else if (scalaClass == classOf[Byte]) {
println("Byte")
}
...
} else if (scalaClass == classOf[Option[Boolean]]) {
println("Boolean")
} else if (scalaClass == classOf[Option[Byte]]) {
println("Byte")
}
...
}
classOf[GenericCaseClass].getDeclaredFields.foreach(
declaredField => {
printType(declaredField)
}
)
初步结果
- 布尔值
- 字节
- 短的
- 诠释
- 长
- 漂浮
- 双倍的
- 字符
- 细绳
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
- 选项[布尔]
当前尝试
我在 if 语句链的开头添加了以下内容,以尝试获取选项的内部类型:
if (scalaClass == classOf[Option[_]]) {
val innerType = field
.getGenericType
.asInstanceOf[ParameterizedType]
.getActualTypeArguments
.head
.getTypeName
println("Option[_] -> " + innerType)
}
但它似乎只适用于字符串:
- 布尔值
- 字节
- 短的
- 诠释
- 长
- 漂浮
- 双倍的
- 字符
- 细绳
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.Object
- 选项[_] -> java.lang.String
注意:我使用的是 Scala 版本 2.11.11。
解决方案
使用 Java 反射很快让我头疼,所以这里有一个非常简单的 Scala 解决方案:
import scala.reflect.runtime.universe._
//--Your case class definition--//
val values = typeOf[GenericCaseClass].members.filterNot(_.isMethod)
def prettyPrintField(symbol: Symbol): Unit = {
val name = symbol.name
val typeSignature: Type = symbol.typeSignature
println(s"$name: $typeSignature")
}
values.foreach(prettyPrintField)
输出:
r : Option[String]
q : Option[Char]
<- rest of fields ->
a : Boolean
推荐阅读
- javascript - 如何将画布上的绘制路径保存为 JavaScript 中的函数?
- python - Python 重载运算符不能在表达式的“两侧”工作
- swift - 谓词错误:实体不符合键“@count”的键值编码
- javascript - 在 JavaScript 中使用正则表达式查找确切的电话号码
- python - 如何选择具有值的最右边的列?
- python - 我想以不同的顺序比较两个不同的数据帧,同时忽略特殊字符、空格。如果相同则更换它
- python - 使用 SKlearn 预训练/重新训练核岭回归
- python - 从目录中查找最新文件
- angular - Angular Preflight 请求添加标头
- python - 如何比较有序字典的键?