Concise use of agents in Java

Source: Internet
Author: User

Agent

Two concepts should be clarified first

Proxy object: An object that intercepts access to the target object

target object: The object to actually access

role of the agent

can be used to strengthen the method;

Dynamic Agent Demo

    

Target object public class target implements itarget{@Overridepublic void Test1 () {System.out.println ("test1 ()" of the target object);}}

  

//Proxy Object Public classProxyDemo1 {@Test Public voidtest1 () {//To create a dynamic proxy object        FinalTarget tar=NewTarget ();//the anonymous inner class is called, and the final decorationITarget newproxyinstance = (itarget) proxy.newproxyinstance (Tar.getclass (). getClassLoader (),//passing a class loader that is consistent with the targetTar.getclass (). Getinterfaces (),//pass a class<?>[] interfaces                                NewInvocationhandler () {//implementing an interface using an anonymous inner class Invocationhandler@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Logic before calling the target method"); Object Invoke=Method.invoke (tar, args); System.out.println ("Logic before calling the target method"); returninvoke;        }                                }                                ); Newproxyinstance.test1 ();//Invoke is actually called under Invocationhandler            }}
Execution results
Test1 () of the logical target object before the call to the target method invokes the logic before the target method

Note : The proxy mode of the JDK implementation of the dynamic proxy target object must have an interface, no interface can not implement the JDK

Version of the dynamic agent.

Concise use of agents in Java

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.