Created
September 7, 2009 13:54
-
-
Save viktorklang/182362 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Test { | |
trait Mapping { | |
def get[T](clazz : Class[T]) : T | |
} | |
trait Injector { | |
protected val mapping : Mapping | |
def inject[T](implicit manifest : scala.reflect.Manifest[T]) = mapping.get(manifest.erasure.asInstanceOf[Class[T]]) | |
} | |
trait ClassPathInjector extends Injector | |
{ | |
val propertyName : String | |
protected lazy val mapping : Mapping = Class.forName(System.getProperty(propertyName)).newInstance.asInstanceOf[Mapping] | |
} | |
//Test sample | |
trait Foo | |
class FooImpl extends Foo | |
object TestInjector extends Injector { | |
protected lazy val mapping = new Mapping { | |
override def get[T](clazz : Class[T]) : T = { | |
val r = clazz match { | |
case x if x.isAssignableFrom(classOf[Foo]) => (new FooImpl) | |
case _ => throw new RuntimeException("Injector failed!") | |
} | |
r.asInstanceOf[T] | |
} | |
} | |
} | |
//Test usage | |
import TestInjector._ | |
val foo = inject[Foo] | |
Console.println(foo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment