Skip to content

Instantly share code, notes, and snippets.

@maxim-s
Created December 22, 2014 10:18
Show Gist options
  • Save maxim-s/b08d397c551eb5a75cd3 to your computer and use it in GitHub Desktop.
Save maxim-s/b08d397c551eb5a75cd3 to your computer and use it in GitHub Desktop.
scala how to get all classes based on ParentModule in the package and creating theirs instances
def getModules(pack:String,args: AnyRef*)(ctor: Int = 0): Seq[ParentModule] = {
var result = ListBuffer[ParentModule]()
val cl = Thread.currentThread.getContextClassLoader
val mirror = runtimeMirror(cl)
val res = cl.getResource(pack.replace('.','/'))
//HACK looking for files from package folder just for classloader
for(f<-Directory(Path(res.getFile)).files){
if (!f.name.contains("$anonfun$"))
mirror.staticClass(pack +"."+ f.name.replace(".class",""))
}
val pkg = mirror.staticPackage(pack)
for(t<-pkg.typeSignature.members) {
if (t.isClass && t.info.baseType(typeOf[ParentModule].typeSymbol) == typeOf[ParentModule]){
result+= mirror.reflectClass(t.asClass).reflectConstructor(t.info.members.filter(m =>m.isMethod && m.asMethod.isConstructor)
.iterator.toSeq(ctor).asMethod)(args: _*).asInstanceOf[ParentModule]
}
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment