The code is in Scala, but hopefully understandable for Java programmers as well.
I have the following class:
class SampleClass {
def test(in: String) = "Hello world!"
}
I have the following code that creates an enhanced instance of this class:
val e = new Enhancer
e.setSuperclass(classOf[SampleClass])
e.setCallback(new Cb)
println(e.create.asInstanceOf[SampleClass].test("foo"))
The callback is as follows:
class Cb extends MethodInterceptor {
override def intercept(obj: Any, m: Method, args: Array[Object], proxy: MethodProxy): Object = {
println(s"$m is called: ${m.getName}")
proxy.invokeSuper(obj, args)
}
}
This works fine. Now, if I instead try to create a class and then a new instance of it, all the methods are called directly, bypassing the callback:
val e = new Enhancer
e.setSuperclass(classOf[SampleClass])
e.setCallbackType(classOf[Cb])
println(e.createClass.newInstance.asInstanceOf[SampleClass].test("foo"))
Why so? How do I create a java.lang.Class
and use its newInstance()
method to generate the enhanced objects?