Collation: Java dynamic agent

Source: Internet
Author: User
Tags object object

1. Define the Business interface
Public InterfaceIPerson {
Public voidsay();
Public voidRun();
Public voidSleep();
}
2. Implementing the Business Interface
Public classPersonimplImplementsIPerson {
@Override
Public voidsay() {
Logutil.e("person say");
}

@Override
Public voidRun() {
Logutil.e("Person Run");
}

@Override
Public voidSleep() {
Logutil.e("Person Sleep");
}
}
3. Define a dynamic proxy class that implementsInvocationhandler Interface
Public classPersonhandleImplementsInvocationhandler {
PrivateObjectObject;//keep the original object of the agent

PublicPersonhandle (Object object) {
Super();
This.Object= Object;//Construction Injection
}

@Override
PublicObjectInvoke(Object Proxy, Method method, Object[] args)throwsThrowable {
Object result=null;

//if it issaymethod, there is a predecessor and a post-operation
if(Method.getname (). Equals ("Say")){
Dobefore ();
Result=method.invoke (Object,Args;
Doafter ();
}

//if it isRunmethod, only the post operation
else if(Method.getname (). Equals ("Run")){
Result=method.invoke (Object,Args;
Doafter ();
}

//if it isSleepmethod, you don't do anything.
else if(Method.getname (). Equals ("Run")){

}
returnResult;
}

private voidDobefore() {
Logutil.e("Before method Invoke");
}

private voidDoafter() {
Logutil.e("After method Invoke");
}
}
4. Scene class
Public classTestClientextendsInstrumentationtestcase {

Public voidTestmain() {
Logutil.e("Testclient:[start]");

IPerson person=NewPersonimpl ();
Invocationhandler handler=NewPersonhandle (person);

IPerson proxy= (IPerson) proxy.newproxyinstance(Person.getclass (). getClassLoader (),Person.getclass (). Getinterfaces (),Handler;
Proxy.say ();
Proxy.run ();

Logutil.e("Testclient:[end]");
}

}
5. Running Results




From for notes (Wiz)

Collation: Java dynamic agent

Related Article

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.