Dynamic proxy, as the name implies is to create a proxy object dynamically, do not need to manually create a proxy class for the proxy class, Java dynamic proxy through the proxy class and the invocation interface implementation, the code is as follows:
Agent interface
Public interface HelloWorld {
public void test ();
}
Handler
public class Testhandler implements Invocationhandler {
public object invoke (object proxy, Method method, object[] args) throws Throwable {
SYSTEM.OUT.PRINTLN ("result");
return null;
}
}
Test class
public class Testmybatis {
public static void Main (string[] args) {
HelloWorld HelloWorld = (HelloWorld) proxy.newproxyinstance (HelloWorld.class.getClassLoader (), New class[]{ Helloworld.class}, New Testhandler ());
Helloworld.test ();
}
}
This example simply generates a proxy class based on the interface and gives it to handler processing (which is how it is done in mybatis) so that the business logic can be written to the Invoke method to achieve low coupling.
The three parameters of the Invoke: Object proxy: An instance of the proxy class, the HelloWorld object in the example above, method method: The execution of the methods, the test method in the example above, object[] Args:method The parameters of the method, The argument in the above example is empty, so here is null.
Java Dynamic Agent Understanding