Last active
October 15, 2015 21:26
-
-
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
This file contains 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 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