The main use of the proxy class in Java.lang.reflect,
Here's how:
Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h)
The following is a test made with JDBC, similar to the Close method of rewriting connection. The code is as follows:
Packagecom.victor_03;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importorg.junit.Test; Public classMypool {PrivateString url = "Jdbc:mysql://192.168.244.144:3306/test"; PrivateString user = "root"; PrivateString password = "123456"; @Test Public voidProxytest ()throwsException {class.forname ("Com.mysql.jdbc.Driver"); FinalConnection conn =drivermanager.getconnection (URL, user, password); Connection Proxy=(Connection) proxy.newproxyinstance (Conn.getclass (). getClassLoader (),//class Loader//The target object implements the interface, because the connection is originally a result, so use this method, if the target object itself is a class, the way to use is: Conn.getclass (). Getinterfaces () NewClass[] {Connection.class }, NewInvocationhandler () {//The transaction processor is automatically triggered when the Conn object method is called@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {Object result=NULL; String MethodName=Method.getname (); if("Close". Equals (MethodName)) {System.out.println ("Start execution of the Close method"); } Else{result=Method.invoke (conn, args); } returnresult; } }); Proxy.close (); }}
Java Dynamic Agent