JDK Dynamic Proxy Example

Source: Internet
Author: User

The proxy class for the JDK dynamic agent must be implemented on the interface. If you want to proxy the class, use the Cglib proxy.

Define an interface first:

 Public Interface Character {    publicvoid  Show ();}

Next, define a class:

 Public class Implements character{    @Override    publicvoid  Show () {        //  TODO auto-generated method stub        System.out.println ("This is A");    }    }

Define the proxy class to implement the Invocationhandler interface:

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classJdkproxyImplements invocationhandler{PrivateObject Delegate;  Publicobject bind (object delegate) { This. Delegate =delegate;
     //using reflection mechanism to generate a proxy object returnProxy.newproxyinstance (Delegate.getclass (). getClassLoader (), Delegate.getclass (). Getinterfaces (), This); } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//TODO auto-generated Method StubObject result =NULL;
System.out.println ("Jdkproxy Invoke");
     //Here is the method that called the target class, so you can insert other transaction logic before and after the method executes, and you can change the parameters passed in and the result returned =Method.invoke (delegate, args); returnresult; }}

Example:

 Public Static void Main (string[] args) {        = (Character) ((new jdkproxy ()). Bind (new  A ()));        C.show ();    }

Printed results:

Jdkproxy Invoke  This is A

JDK Dynamic Proxy Example

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.