Thursday, September 2, 2010

Load Classes from list of directories

The following code loads all classes recursively in a list of directory separated by file separator. For example c:/dev/project1;c:/dev/project2 retrieves all classes in the two directories recursively.



 2 import java.io.File
 3 import java.io.FileInputStream
 4 
 5 // The class loader that allows to load class from bytes.
 6 object CLoader extends ClassLoader {}
 7   
 8 class ClassRepository(inpath: String) {
 9   def classes = allClasses(inpath)
10   
11   def CLASS_EXT = ".class"
12   
13   def allClasses(inpath: String) : Seq[Class[_]] = {
14      for{ path <- inpath.split(File.pathSeparator)  
15           c <- getAllClasses( new File(path), Nil)
16       } yield c
17   }
18   
19   def getAllClasses(f: File, path: List[String]): List[Class[_]] = {
20     if (f.isFile && f.getName.endsWith(CLASS_EXT)) {
21       val className = 
22             path.reverse.mkString(".") + 
23               (if (path.size == 0) "" else ".") +
24                 f.getName.dropRight(CLASS_EXT.length)
25       List(CLoader.loadClass(className))
26     } 
27     else if (f.isDirectory) {
28       val files = f.listFiles
29       files.foldLeft(Nil: List[Class[_]])(
30        (lst,file) => {
31           if (file.isDirectory)
32             getAllClasses(file, file.getName::path) ::: lst
33           else
34             getAllClasses(file, path) ::: lst
35        }
36       )
37     }
38     else 
39       Nil
40   }
41 }

No comments: