Get all the classes that implements a trait in Scala using reflection

后端 未结 2 713
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 11:09

I want to list out all the case classes which implements a particular trait. I am currently using Clapper ClassUtil for doing that. I am able to get the case classes that ar

2条回答
  •  执笔经年
    2020-12-15 11:56

    Looking at the source code, the problem seems to be that it doesn't follow the interfaces hierarchy. If you do that, you find all instances:

    package foo
    
    import java.io.File
    
    import org.clapper.classutil.{ClassFinder, ClassInfo}
    
    object Main extends App {
      val jar     = new File("target/scala-2.11/class_test_2.11-0.1.0.jar")
      val finder  = ClassFinder(jar :: Nil)
      val classes = ClassFinder.classInfoMap(finder.getClasses().iterator)
      val impl    = find("foo.NamedEntity", classes)
      impl.foreach(println)
    
      def find(ancestor: String, classes: Map[String, ClassInfo]): List[ClassInfo] =
        classes.get(ancestor).fold(List.empty[ClassInfo]) { ancestorInfo =>
          val ancestorName = ancestorInfo.name
    
          def compare(info: ClassInfo): Boolean =
            info.name == ancestorName ||
            (info.superClassName :: info.interfaces).exists {
              n => classes.get(n).exists(compare)
            }
    
          val it = classes.valuesIterator
          it.filter { info => info.isConcrete && compare(info) } .toList
        }
    }
    

提交回复
热议问题