The AOP of Java

Source: Internet
Author: User

AOP (aspect-oriented programming), the official definition will not speak, but Baidu itself. As I understand it, the code fragment is injected dynamically into a certain piece of code that is known. The advantage of this is that the functionality of the original business can be expanded without changing the original code.

AOP is implemented in two ways:

1. Dynamic Agent

Example:

Let's say we print a row of logs for each method entry and exit of a class, but we can't change the original code.

1  Packagecom;2 3  Public InterfaceALGORITHMITF4 {5 voidAdd ();6 7 voiddel ();8 9 voidupdate ();Ten  One voidfind (); A } -  -  Packagecom; the  -  Public classAlgorithmImplementsALGORITHMITF - { -  Public voidAdd () + { -System.out.println ("Add ..."); + } A  Public voiddel () at { -System.out.println ("Del ..."); - } -  Public voidUpdate () - { -SYSTEM.OUT.PRINTLN ("Update ..."); in } -  Public voidFind () to { +System.out.println ("Find ..."); - } the } *  $  Panax Notoginseng  -  Packagecom; the  + ImportJava.lang.reflect.InvocationHandler; A ImportJava.lang.reflect.Method; the ImportJava.lang.reflect.Proxy; +  -  Public classAopdyproxy<t>ImplementsInvocationhandler $ { $ PrivateT o; -  -  PublicT CreateInstance (T T) the { -o=T;Wuyi returnT (Proxy.newproxyinstance (O.getclass (). getClassLoader (), O.getclass (). Getinterfaces (), This)); the } -  Wu @Override -  PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable About { $Object re=NULL; -System.out.println (Method.getname () + "enter"); -Re=Method.invoke (o, args); -System.out.println (Method.getname () + "Exit"); A returnre; + } the  Public Static voidMain (string[] args) - { $Aopdyproxy<algorithmitf> p=NewAopdyproxy<algorithmitf>(); theALGORITHMITF A=p.createinstance (Newalgorithm ()); the A.add (); the a.update (); the } -  in}
View Code

2. Static Proxy

The AOP of Java

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.