Skip to content

Instantly share code, notes, and snippets.

@rahilb
Created October 29, 2015 15:54
Show Gist options
  • Save rahilb/05cfa91fd084d0f32d19 to your computer and use it in GitHub Desktop.
Save rahilb/05cfa91fd084d0f32d19 to your computer and use it in GitHub Desktop.
overwrite object values
import sun.misc.Unsafe
object Foo {
val len: String => Int = {s => s.length}
def bar(s: String) = s.length
}
Foo.len("foo") // 3
val unsafe = {
val f = classOf[Unsafe].getDeclaredField("theUnsafe")
f.setAccessible(true)
f.get(null).asInstanceOf[Unsafe]
}
val offset = unsafe.objectFieldOffset(Foo.getClass.getDeclaredField("foo"))
val doubleLen: String => Int = { s=> s.length * 2}
unsafe.putObject(Foo, offset, doubleLen)
Foo.len("foo") // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment