Skip to content

Commit

Permalink
Allows creation of classloaders with given parent.
Browse files Browse the repository at this point in the history
  • Loading branch information
psuter committed Jan 10, 2013
1 parent 21cef90 commit de0ab17
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/main/scala/cafebabe/CafebabeClassLoader.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@ import scala.collection.mutable.{Map=>MutableMap}

/** A `ClassLoader` with the capability for loading cafebabe
* `ClassFile`s directly from memory. */
class CafebabeClassLoader extends ClassLoader {
private val classes : MutableMap[String,Array[Byte]] = MutableMap.empty
class CafebabeClassLoader(parent : ClassLoader) extends ClassLoader(parent) {
def this() {
this(ClassLoader.getSystemClassLoader())
}

private val classBytes : MutableMap[String,Array[Byte]] = MutableMap.empty

def register(classFile : ClassFile) {
val name = classFile.className
if(classBytes.isDefinedAt(name)) {
throw new IllegalArgumentException("Cannot define the same class twice (%s).".format(name))
}

val byteStream = (new ByteStream) << classFile
classes(classFile.className) = byteStream.getBytes
classBytes(name) = byteStream.getBytes
}

override def findClass(name : String) : Class[_] = {
classes.get(name) match {
case Some(ba) => defineClass(name, ba, 0, ba.length)
classBytes.get(name) match {
case Some(ba) =>
defineClass(name, ba, 0, ba.length)

case None => super.findClass(name)
}
}
Expand Down

0 comments on commit de0ab17

Please sign in to comment.