I know cglib proxying works by subclassing target class and overriding target class' methods.
Can anyone tell how exactly dynamic proxy works? I know it uses interface for proxying, but how exactly method invokation happens through proxy?
Using Proxy.newProxyInstance()
you can ask for a proxy implementing required interfaces. You need to pass an InvocationHandler
too, which is called every time you call any proxy method. Then, in your handler, you know which method is called and its parameters, so you can do what you desire, including using a target object.
How does Java handle this? Well, it's done natively, just as the internals of reflection
and a lot of basic functionality. So, you can emulate this behavior using plain Java.
Extended info here.