lundi 16 avril 2018

How do I set a Generic type as a Reflect type variable?

I have a class that accepts Generic types, but I want to pass in the generic type to the class at runtime, using a Reflect.Type variable. The class is documented here: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html

I wrote a function that accepts a list of Generic type class names as Strings, and maps them to the corresponding Generic Type using reflection

def getGenericTypeByName(names: Map[String, String]): Map[String, reflect.Type] = {

val declaredFields = Types.getClass.getDeclaredFields.toSeq;

val types: Map[String, reflect.Type] = names.map(s => {
  val fieldType = declaredFields.find(_.getName.equals(s._2)).getOrElse(null);
  if (fieldType != null) {
    (s._1, fieldType.getGenericType);
  } else {
    (s._1, null);
  }
});

The return value is a Map of Reflect.Type, which should be passable to a Generic type parameter in a class, so I should be able to do this:

types.map(s => this.GenericClassMap.get(s._1).get.read[s._2]());

But when I compile, I get the error Cannot resolve symbol _2

What is missing here? _2 should be accesible since it's a map, and it's of a reflect type which I think should match the generic type too.





Aucun commentaire:

Enregistrer un commentaire