lundi 23 juillet 2018

Determining the type of an Option field in a Scala class

Question

How do you determine the type of each field of a class?

Given the following case class:

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]
)

Initial Attempt

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)
    }
)

Initial Result

  • Boolean
  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • Char
  • String
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]

Current Attempt

I added the following to the beginning of the if-statement chain in an attempt to get the inner type of the Options:

if (scalaClass == classOf[Option[_]]) {
    val innerType = field
        .getGenericType
        .asInstanceOf[ParameterizedType]
        .getActualTypeArguments
        .head
        .getTypeName

    println("Option[_] -> " + innerType)
}

But it appears to only work for Strings:

  • Boolean
  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • Char
  • String
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.String

Note: I'm using Scala version 2.11.11.





Aucun commentaire:

Enregistrer un commentaire