Java Dynamic Agent

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.