Skip to content

Instantly share code, notes, and snippets.

@hisui
Created February 16, 2012 08:35
Show Gist options
  • Save hisui/1843338 to your computer and use it in GitHub Desktop.
Save hisui/1843338 to your computer and use it in GitHub Desktop.
test
import java.lang.reflect.{Proxy, InvocationHandler, Method}
object Prototype {
def clone[T](base:T, content:AnyRef)(implicit manifest:ClassManifest[T]):T = {
val metaclass = manifest.erasure
Proxy.newProxyInstance(metaclass.getClassLoader, Array(metaclass),
new InvocationHandler {
override def invoke(proxy:Object, method:Method, args:Array[Object]):Object = {
val a = if(args != null) args else Array[Object]()
val callee = content.getClass.getDeclaredMethod(method.getName, a.map(_ getClass):_*)
callee.setAccessible(true)
callee.invoke(content, a:_*)
}
}).asInstanceOf[T]
}
}
trait FooLike {
def x:String
def y:String
}
case class Foo(hoge:String, hige:String) extends FooLike
val a:FooLike = Foo("foo","bar")
var b = Prototype.clone(a, new {
val x = "baz"
})
println(a.x +", "+ a.y)
println(b.x +", "+ b.y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment