Java-implemented interceptors

Source: Internet
Author: User

/**

* Dynamically generate a proxy class object and bind the proxy class and the proxy processor

*

* @param Business

* @return Proxy class object

*/

public object bind (object business) {

this.business = business;

Return Proxy.newproxyinstance (

ClassLoader of the proxy class

Business.getclass (). getClassLoader (),

To be proxied interfaces, this method returns objects that automatically claim to implement these interfaces

Business.getclass (). Getinterfaces (),

Agent Processor Object

this);

}

/**

* The method that the agent wants to invoke and calls the connector before and after the method call.

*

* @param proxy class object

* @param method is the proxy interface

* @param the parameters of the args Proxy interface method

* Results returned by @return method call

* @throws Throwable

*/

public object invoke (object proxy, Method method, object[] args) throws Throwable {

Object result = null;

Interceptor.before ();

Result=method.invoke (Business,args);

Interceptor.after ();

return null; To change body of implemented methods use File | Settings | File Templates.

}

}

Third, interceptors: ordinary JavaBean, will automatically intercept and execute some of their methods before or after calling the business method.

/**

* Interception Device

*/

public class Interceptorclass {

public void before () {

System.out.println ("Interceptor Interceptorclass method call: Before ()!");

}

public void after () {

System.out.println ("Interceptor Interceptorclass method invocation: After ()!");

}

}

Iv. Analog Client: The entry to perform business processing.

/**

* Client

*/

public class Client {

public static void Main (String args[]) {

Dynamicproxyhandler handler = new Dynamicproxyhandler ();

Businessinterface business = new Businessclass ();

Businessinterface businessproxy = (businessinterface) handler.bind (business);

Businessproxy.dosomething ();

}

}

Java-implemented interceptors

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.