title: How to obtain generic type at runtime in Scala
body: <p>I have a following class</p>
  
  <pre class="lang-scala prettyprint-override"><code>package myapp.model
  
  case class Person(
   name: String,
   age: Option[Int]
  )
  </code></pre>
  
  <p>I would like to implement following function:</p>
  
  <pre class="lang-scala prettyprint-override"><code>def getFieldClass(className: String, fieldName:String): java.lang.Class[_] = {
      // case normal field return its class
      // case Option field return generic type of Option
  }
  </code></pre>
  
  <p>So that for following input:</p>
  
  <ul>
  <li>className="myapp.model.Person"</li>
  <li>fieldName="age"</li>
  </ul>
  
  <p>the function will return class object: scala.Int</p>
  
  <hr>
  
  <p>Solution with Java Reflection API doesn't work well, it returns java.lang.Object for Option[Int]:</p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>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.</p>