mercredi 27 avril 2016

Get ancestor types with Scala reflection

Given a Scala TypeTag, is there a way to get the TypeTags of the type's ancestors, cf. java.lang.Class.getSuperclass() and java.lang.Class.getInterfaces()?

For instance, it possible to write a method with this signature --

  def allAncestors[C1, C2](
    implicit startFrom: ru.TypeTag[C1],
             stopAt: ru.TypeTag[C2]
  ): Set[ru.TypeTag[_]]

-- that produces results more or less equivalent to the Java method below?

Set<Class<?>> allAncestors(Class<?> startFrom, Class<?> stopAt) {
    if (startFrom == stopAt) {
        return Collections.singleton(stopAt);
    }
    Set<Class<?>> immediates = new HashSet<>(Arrays.asList(startFrom.getInterfaces()));
    Class<?> superclass = startFrom.getSuperclass();
    if (superclass != null) {
        immediates.add(superclass);
    }
    Set<Class<?>> ancestors = new HashSet<>(immediates);
    for (Class<?> immediate : immediates) {
        ancestors.addAll(allAncestors(immediate, stopAt));
    }
    return ancestors;
}

(Note: the Java code is untested and may be buggy, but you can see what I'm getting at.)





Aucun commentaire:

Enregistrer un commentaire