I have a following class
package myapp.model
case class Person(
name: String,
age: Option[Int]
)
I would like to implement following function:
def getFieldClass(className: String, fieldName:String): java.lang.Class[_] = {
// case normal field return its class
// case Option field return generic type of Option
}
So that for following input:
- className="myapp.model.Person"
- fieldName="age"
the function will return class object: scala.Int
Solution with Java Reflection API doesn't work well, it returns java.lang.Object for Option[Int]:
def getFieldClass(className: String, fieldName:String): java.lang.Class[_] = {
val cls = java.lang.Class.forName(className)
val pt = cls.getDeclaredField(fieldName).getGenericType.asInstanceOf[java.lang.reflect.ParameterizedType]
val tpe = pt.getActualTypeArguments()(0);
java.lang.Class.forName(tpe.getTypeName)
}
I'm writing part of deserializing feature and I don't have the object to check it's type, I have only a class name.