简体   繁体   中英

Java to Scala type conversion - collection of reflected classes

I use org.reflections to scan a package in my project and get all classes that extend a certain trait, like so:

val reflections = new Reflections("classpath")<br>
val classSet = reflections.getSubTypesOf(classOf[Validation])

I end up with a util.Set[Class[_ : Validation]]
If i do classSet.toSet.map(x => x.getName -> x).toMap using JavaConversions i get a 'missing parameter type' error.

If i do classSet.toSet.map(x => Map(x.getName -> x)).reduce(_ ++ _) i get the same error.
If i replace the toSet to toList i get a 'type mismatch' error.

if i do classSet.toList.map(x => (x.getName, x)).toMap , i get the following error:
Cannot prove that (String, Class[?O]) forSome { type ?O <: com.common.Validation } <:< (T,U). not enough arguments for method toMap: (implicit ev: <:<[(String, Class[?0]) forSome { type ?0 <: com.common.Validation },(T,U)])scala.collection.immutable.Map[T,U]. Unspecified value parameter ev.


I want to convert this set to a map of the class name as key and the reflected class as value.
Note - when i build a map like: var classMap = Map[String, Class[_ <: Validation]]() and then pushing every element into this map, by iterating over the Set . I can't access the class's methods i implemented from the Trait .

What helps in such cases in to explicity specify the types when using the toSet and toMap conversions:

import org.reflections.Reflections
import scala.collection.JavaConversions._

trait Validation

val reflections = new Reflections("classpath")
val javaClassSet = reflections.getSubTypesOf(classOf[Validation])
val scalaClassSet = javaClassSet.toSet[Class[_ <: Validation]]
scalaClassSet.map(x => x.getName -> x).toMap[String, Class[_ <: Validation]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM