Skip to content

Instantly share code, notes, and snippets.

@smithjessk
Last active October 15, 2015 21:26
Show Gist options
  • Save smithjessk/9999619733b28b39f663 to your computer and use it in GitHub Desktop.
Save smithjessk/9999619733b28b39f663 to your computer and use it in GitHub Desktop.
An interesting attempt at companion object manipulation. Note that this gets different results when interpreted and when compiled. companionOf is taken from http://stackoverflow.com/a/9174777
object CC {
def companionOf[T : Manifest] : Option[AnyRef] = try {
val classOfT = implicitly[Manifest[T]].erasure
val companionClassName = classOfT.getName + "$"
val companionClass = Class.forName(companionClassName)
val moduleField = companionClass.getField("MODULE$")
Some(moduleField.get(null))
} catch {
case e => None
}
def main(args: Array[String]) = {
case class A(i: Int)
println(companionOf[A] collect { case a: A.type => a(1) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment