Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to obtain the raw datatype of a parameter of a field that is specialized in Scala via reflection?
    primarykey
    data
    text
    <p>I have a class with a field that is specialized and is using a raw datatype. For instance a Tuple2[Int, String]:</p> <pre><code>scala&gt; class TupleReflection(val tuple: Tuple2[Int, String]) defined class TupleReflection scala&gt; val refl = new TupleReflection((5, "hello")) refl: TupleReflection = TupleReflection@1a597ec8 </code></pre> <p>I want to use reflection now to find out the type parameters of the Tuple2 inside my 'refl' instance. (I cheat a little using 'head' to get the field because I know it's the only one.)</p> <pre><code>scala&gt; val field = refl.getClass.getDeclaredFields.head field: java.lang.reflect.Field = private final scala.Tuple2 TupleReflection.tuple </code></pre> <p>Now that I have the field I can query the generic types.</p> <pre><code>scala&gt; field.getGenericType res41: java.lang.reflect.Type = scala.Tuple2&lt;java.lang.Object, java.lang.String&gt; </code></pre> <p>The problem now is that the first type is Object. Is there a way to know, via reflection alone, the real type (Int) of that parameter?</p> <h1>Update:</h1> <p>I'm using this in a context of automatic serialization within my own API. Given a class marked with @Serializable I can serialize it. To do so I must build a tree of the fields and types of the class recursively using reflection so I can do a deep serialization.</p> <p>If I'm working directly with a @Specialized class it works because the types are explicit and known at compile time at the invocation site. If a field in the hierarchy is @specialized I have no way to tell via reflection. Querying the fields or methods declared in a class doesn't yield the correct value. The type is present in runtime but only on the instance held in the field, not on the declaration of the field itself. Thus if the instance is null and can't do a "getClass" I can't know the correct types by reflection alone.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload