diff options
author | ehilsdal <ehilsdal> | 2003-04-08 21:59:39 +0000 |
---|---|---|
committer | ehilsdal <ehilsdal> | 2003-04-08 21:59:39 +0000 |
commit | e2af842ae7dbf3b0315a5f73d3d5ec9b7f041556 (patch) | |
tree | a4e993a588298b0d6babdf643de8d35991a2ebd6 /docs | |
parent | f11709f8bc26a053ff573039cc0b5ee887c005ff (diff) | |
download | aspectj-e2af842ae7dbf3b0315a5f73d3d5ec9b7f041556.tar.gz aspectj-e2af842ae7dbf3b0315a5f73d3d5ec9b7f041556.zip |
folded in material from README-11.html
finally totally and completely stomped out "introduction"
minor formatting changes
generating better filenames for the progguide
added A4 version of quick reference
Diffstat (limited to 'docs')
37 files changed, 4414 insertions, 3809 deletions
diff --git a/docs/build.xml b/docs/build.xml index 7097fe443..d5be65d29 100644 --- a/docs/build.xml +++ b/docs/build.xml @@ -296,6 +296,7 @@ <arg value="${xml-source-dir}/${xml-source-root}"/> <arg value="${xsl-source-file}"/> <arg value="base.dir=${xml-target-dir}/"/> + <arg value="use.id.as.filename=1"/> </java> </target> diff --git a/docs/devGuideDB/devguide.xml b/docs/devGuideDB/devguide.xml index 8107eaa90..1c93ce2cb 100644 --- a/docs/devGuideDB/devguide.xml +++ b/docs/devGuideDB/devguide.xml @@ -20,12 +20,12 @@ <authorgroup> <author> - <othername>the AspectJ Team</othername> + <othername>the AspectJ Team</othername> </author> </authorgroup> <legalnotice> - <para>Copyright (c) 1998-2001 Xerox Corporation, + <para>Copyright (c) 1998-2001 Xerox Corporation, 2002 Palo Alto Research Center, Incorporated, 2003 Contributors. All rights reserved. @@ -34,14 +34,13 @@ <abstract> <para> - This guide describes the tools in the AspectJ 1.1 development environment. - See also - <ulink url="../progguide/index.html">The AspectJ Programming Guide</ulink>, - the documentation for the AspectJ - <ulink url="../ant-tasks.html">Ant tasks</ulink>, - and the documentation available with the AspectJ support available for - various integrated development environments - (e.g., Eclipse, Emacs, JBuilder, and NetBeans). + This guide describes the tools in the AspectJ 1.1 development + environment. See also <ulink url="../progguide/index.html">The + AspectJ Programming Guide</ulink>, the documentation for the + AspectJ <ulink url="../ant-tasks.html">Ant tasks</ulink>, and the + documentation available with the AspectJ support available for + various integrated development environments (e.g., Eclipse, Emacs, + JBuilder, and NetBeans). </para> </abstract> </bookinfo> diff --git a/docs/dist/doc/examples/bean/BoundPoint.java b/docs/dist/doc/examples/bean/BoundPoint.java index c247ca9cd..e5d9ab8c6 100644 --- a/docs/dist/doc/examples/bean/BoundPoint.java +++ b/docs/dist/doc/examples/bean/BoundPoint.java @@ -10,19 +10,20 @@ * warranty about the software, its performance or its conformity to any * specification. */ + package bean; import java.beans.*; import java.io.Serializable; /* - * Add bound properties and serialization to point objects + * Add bound properties and serialization to point objects */ aspect BoundPoint { /* * privately introduce a field into Point to hold the property - * change support object. `this' is a reference to a Point object. + * change support object. `this' is a reference to a Point object. */ private PropertyChangeSupport Point.support = new PropertyChangeSupport(this); @@ -34,13 +35,13 @@ aspect BoundPoint { support.addPropertyChangeListener(listener); } - public void Point.addPropertyChangeListener(String propertyName, + public void Point.addPropertyChangeListener(String propertyName, PropertyChangeListener listener){ - + support.addPropertyChangeListener(propertyName, listener); } - public void Point.removePropertyChangeListener(String propertyName, + public void Point.removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { support.removePropertyChangeListener(propertyName, listener); } @@ -63,31 +64,31 @@ aspect BoundPoint { /** * Advice to get the property change event fired when the - * setters are called. It's around advice because you need + * setters are called. It's around advice because you need * the old value of the property. */ void around(Point p): setter(p) { - String propertyName = + String propertyName = thisJoinPointStaticPart.getSignature().getName().substring("set".length()); - int oldX = p.getX(); - int oldY = p.getY(); - proceed(p); - if (propertyName.equals("X")){ + int oldX = p.getX(); + int oldY = p.getY(); + proceed(p); + if (propertyName.equals("X")){ firePropertyChange(p, propertyName, oldX, p.getX()); - } else { + } else { firePropertyChange(p, propertyName, oldY, p.getY()); - } + } } /* * Utility to fire the property change event. */ - void firePropertyChange(Point p, - String property, - double oldval, + void firePropertyChange(Point p, + String property, + double oldval, double newval) { - p.support.firePropertyChange(property, - new Double(oldval), + p.support.firePropertyChange(property, + new Double(oldval), new Double(newval)); } } diff --git a/docs/dist/doc/examples/bean/Demo.java b/docs/dist/doc/examples/bean/Demo.java index 767409878..e16be245e 100644 --- a/docs/dist/doc/examples/bean/Demo.java +++ b/docs/dist/doc/examples/bean/Demo.java @@ -1,13 +1,12 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United States export control laws. - */ + package bean; import java.beans.*; @@ -22,62 +21,60 @@ public class Demo implements PropertyChangeListener { * this method reports that a propery has changed */ public void propertyChange(PropertyChangeEvent e){ - System.out.println("Property " + e.getPropertyName() + " changed from " + - e.getOldValue() + " to " + e.getNewValue() ); + System.out.println("Property " + e.getPropertyName() + " changed from " + + e.getOldValue() + " to " + e.getNewValue() ); } /** * main: test the program */ public static void main(String[] args){ - Point p1 = new Point(); - p1.addPropertyChangeListener(new Demo()); - System.out.println("p1 =" + p1); - p1.setRectangular(5,2); - System.out.println("p1 =" + p1); - p1.setX( 6 ); - p1.setY( 3 ); - System.out.println("p1 =" + p1); - p1.offset(6,4); - System.out.println("p1 =" + p1); - save(p1, fileName); - Point p2 = (Point) restore(fileName); - System.out.println("Had: " + p1); - System.out.println("Got: " + p2); + Point p1 = new Point(); + p1.addPropertyChangeListener(new Demo()); + System.out.println("p1 =" + p1); + p1.setRectangular(5,2); + System.out.println("p1 =" + p1); + p1.setX( 6 ); + p1.setY( 3 ); + System.out.println("p1 =" + p1); + p1.offset(6,4); + System.out.println("p1 =" + p1); + save(p1, fileName); + Point p2 = (Point) restore(fileName); + System.out.println("Had: " + p1); + System.out.println("Got: " + p2); } /** * Save a serializable object to a file */ static void save(Serializable p, String fn){ - try { - System.out.println("Writing to file: " + p); - FileOutputStream fo = new FileOutputStream(fn); - ObjectOutputStream so = new ObjectOutputStream(fo); - so.writeObject(p); - so.flush(); - } catch (Exception e) { - System.out.println(e); - System.exit(1); - } + try { + System.out.println("Writing to file: " + p); + FileOutputStream fo = new FileOutputStream(fn); + ObjectOutputStream so = new ObjectOutputStream(fo); + so.writeObject(p); + so.flush(); + } catch (Exception e) { + System.out.println(e); + System.exit(1); + } } /** * Restore a serializable object from the file */ static Object restore(String fn){ - try { - Object result; - System.out.println("Reading from file: " + fn); - FileInputStream fi = new FileInputStream(fn); - ObjectInputStream si = new ObjectInputStream(fi); - return si.readObject(); - } catch (Exception e) { - System.out.println(e); - System.exit(1); - } - return null; + try { + Object result; + System.out.println("Reading from file: " + fn); + FileInputStream fi = new FileInputStream(fn); + ObjectInputStream si = new ObjectInputStream(fi); + return si.readObject(); + } catch (Exception e) { + System.out.println(e); + System.exit(1); + } + return null; } - - } diff --git a/docs/dist/doc/examples/bean/Point.java b/docs/dist/doc/examples/bean/Point.java index d5040c2bf..a6ea703cd 100644 --- a/docs/dist/doc/examples/bean/Point.java +++ b/docs/dist/doc/examples/bean/Point.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,7 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - */ package bean; @@ -23,54 +21,49 @@ class Point { * Return the X coordinate */ public int getX(){ - return x; + return x; } /** * Return the y coordinate */ public int getY(){ - return y; + return y; } /** * Set the x and y coordinates */ public void setRectangular(int newX, int newY){ - setX(newX); - setY(newY); + setX(newX); + setY(newY); } /** * Set the X coordinate */ public void setX(int newX) { - x = newX; + x = newX; } /** * set the y coordinate */ public void setY(int newY) { - y = newY; + y = newY; } - /** * Move the point by the specified x and y offset */ public void offset(int deltaX, int deltaY){ - setRectangular(x + deltaX, y + deltaY); + setRectangular(x + deltaX, y + deltaY); } - /** - * MAke a string of this + * Make a string of this */ public String toString(){ - return "(" + getX() + ", " + getY() + ")" ; + return "(" + getX() + ", " + getY() + ")" ; } - - - } diff --git a/docs/dist/doc/examples/introduction/CloneablePoint.java b/docs/dist/doc/examples/introduction/CloneablePoint.java index 85fa4faf0..c34509850 100644 --- a/docs/dist/doc/examples/introduction/CloneablePoint.java +++ b/docs/dist/doc/examples/introduction/CloneablePoint.java @@ -30,7 +30,7 @@ public aspect CloneablePoint { p1.setPolar(Math.PI, 1.0); try { - p2 = (Point)p1.clone(); + p2 = (Point)p1.clone(); } catch (CloneNotSupportedException e) {} System.out.println("p1 =" + p1 ); System.out.println("p2 =" + p2 ); diff --git a/docs/dist/doc/examples/observer/Button.java b/docs/dist/doc/examples/observer/Button.java index 086a89e24..79b33caa9 100644 --- a/docs/dist/doc/examples/observer/Button.java +++ b/docs/dist/doc/examples/observer/Button.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -Button.java - */ @@ -28,18 +24,17 @@ class Button extends java.awt.Button { static final String defaultText = "cycle color"; Button(Display display) { - super(); - setLabel(defaultText); - setBackground(defaultBackgroundColor); - setForeground(defaultForegroundColor); - addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - Button.this.click(); - } - }); - display.addToFrame(this); + super(); + setLabel(defaultText); + setBackground(defaultBackgroundColor); + setForeground(defaultForegroundColor); + addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Button.this.click(); + } + }); + display.addToFrame(this); } public void click() {} - } diff --git a/docs/dist/doc/examples/observer/ColorLabel.java b/docs/dist/doc/examples/observer/ColorLabel.java index 7b0c05fc9..5709545f2 100644 --- a/docs/dist/doc/examples/observer/ColorLabel.java +++ b/docs/dist/doc/examples/observer/ColorLabel.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -ColorLabel.java - */ package observer; @@ -21,20 +17,18 @@ import java.awt.Label; class ColorLabel extends Label { ColorLabel(Display display) { - super(); - display.addToFrame(this); + super(); + display.addToFrame(this); } final static Color[] colors = {Color.red, Color.blue, - Color.green, Color.magenta}; + Color.green, Color.magenta}; private int colorIndex = 0; private int cycleCount = 0; void colorCycle() { - cycleCount++; - colorIndex = (colorIndex + 1) % colors.length; - setBackground(colors[colorIndex]); - setText("" + cycleCount); + cycleCount++; + colorIndex = (colorIndex + 1) % colors.length; + setBackground(colors[colorIndex]); + setText("" + cycleCount); } } - - diff --git a/docs/dist/doc/examples/observer/Demo.java b/docs/dist/doc/examples/observer/Demo.java index b25552478..03be6a614 100644 --- a/docs/dist/doc/examples/observer/Demo.java +++ b/docs/dist/doc/examples/observer/Demo.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -Demo.java - */ package observer; @@ -19,16 +15,15 @@ package observer; public class Demo { public static void main(String[] args) { - Display display = new Display(); - Button b1 = new Button(display); - Button b2 = new Button(display); - ColorLabel c1 = new ColorLabel(display); - ColorLabel c2 = new ColorLabel(display); - ColorLabel c3 = new ColorLabel(display); + Display display = new Display(); + Button b1 = new Button(display); + Button b2 = new Button(display); + ColorLabel c1 = new ColorLabel(display); + ColorLabel c2 = new ColorLabel(display); + ColorLabel c3 = new ColorLabel(display); - b1.addObserver(c1); - b1.addObserver(c2); - b2.addObserver(c3); + b1.addObserver(c1); + b1.addObserver(c2); + b2.addObserver(c3); } } - diff --git a/docs/dist/doc/examples/observer/Display.java b/docs/dist/doc/examples/observer/Display.java index d7f4d479c..67ed2cb5b 100644 --- a/docs/dist/doc/examples/observer/Display.java +++ b/docs/dist/doc/examples/observer/Display.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -Display.java - */ package observer; @@ -34,19 +30,17 @@ class Display extends Panel { protected Frame frame = new Frame("Subject/Observer Demo"); Display() { - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);} - }); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) {System.exit(0);} + }); - frame.add(this, BorderLayout.CENTER); - frame.pack(); - frame.setVisible(true); + frame.add(this, BorderLayout.CENTER); + frame.pack(); + frame.setVisible(true); } void addToFrame(Component c) { - add(c); - frame.pack(); - } + add(c); + frame.pack(); + } } - - diff --git a/docs/dist/doc/examples/observer/Observer.java b/docs/dist/doc/examples/observer/Observer.java index 58ae44916..2851ebe17 100644 --- a/docs/dist/doc/examples/observer/Observer.java +++ b/docs/dist/doc/examples/observer/Observer.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -Observer.java - */ package observer; diff --git a/docs/dist/doc/examples/observer/Subject.java b/docs/dist/doc/examples/observer/Subject.java index 5d80b1e09..d6c144e38 100644 --- a/docs/dist/doc/examples/observer/Subject.java +++ b/docs/dist/doc/examples/observer/Subject.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,10 +8,8 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -Subject.java - */ + package observer; import java.util.Vector; diff --git a/docs/dist/doc/examples/observer/SubjectObserverProtocol.java b/docs/dist/doc/examples/observer/SubjectObserverProtocol.java index 73f730e09..05e54d76c 100644 --- a/docs/dist/doc/examples/observer/SubjectObserverProtocol.java +++ b/docs/dist/doc/examples/observer/SubjectObserverProtocol.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -SubjectObserverProtocol.java - */ package observer; @@ -23,25 +19,23 @@ abstract aspect SubjectObserverProtocol { abstract pointcut stateChanges(Subject s); after(Subject s): stateChanges(s) { - for (int i = 0; i < s.getObservers().size(); i++) { - ((Observer)s.getObservers().elementAt(i)).update(); - } + for (int i = 0; i < s.getObservers().size(); i++) { + ((Observer)s.getObservers().elementAt(i)).update(); + } } private Vector Subject.observers = new Vector(); - public void Subject.addObserver(Observer obs) { - observers.addElement(obs); - obs.setSubject(this); + public void Subject.addObserver(Observer obs) { + observers.addElement(obs); + obs.setSubject(this); } - public void Subject.removeObserver(Observer obs) { - observers.removeElement(obs); - obs.setSubject(null); + public void Subject.removeObserver(Observer obs) { + observers.removeElement(obs); + obs.setSubject(null); } public Vector Subject.getObservers() { return observers; } private Subject Observer.subject = null; public void Observer.setSubject(Subject s) { subject = s; } public Subject Observer.getSubject() { return subject; } - } - diff --git a/docs/dist/doc/examples/observer/SubjectObserverProtocolImpl.java b/docs/dist/doc/examples/observer/SubjectObserverProtocolImpl.java index 01f0c38fc..2bc75918c 100644 --- a/docs/dist/doc/examples/observer/SubjectObserverProtocolImpl.java +++ b/docs/dist/doc/examples/observer/SubjectObserverProtocolImpl.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,9 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -SubjectObserverProtocolImpl.java - */ package observer; @@ -25,12 +21,11 @@ aspect SubjectObserverProtocolImpl extends SubjectObserverProtocol { declare parents: ColorLabel implements Observer; public void ColorLabel.update() { - colorCycle(); + colorCycle(); } - pointcut stateChanges(Subject s): - target(s) && - call(void Button.click()); + pointcut stateChanges(Subject s): + target(s) && + call(void Button.click()); } - diff --git a/docs/dist/doc/examples/telecom/Billing.java b/docs/dist/doc/examples/telecom/Billing.java index a87d73998..651d64b36 100644 --- a/docs/dist/doc/examples/telecom/Billing.java +++ b/docs/dist/doc/examples/telecom/Billing.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,11 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package telecom; @@ -29,13 +23,12 @@ package telecom; * it depends only on timing and on the type of the connection. */ public aspect Billing { - // domination required to get advice on endtiming in the right order + // precedence required to get advice on endtiming in the right order declare precedence: Billing, Timing; public static final long LOCAL_RATE = 3; public static final long LONG_DISTANCE_RATE = 10; - public Customer Connection.payer; public Customer getPayer(Connection conn) { return conn.payer; } /** diff --git a/docs/dist/doc/examples/telecom/TimerLog.java b/docs/dist/doc/examples/telecom/TimerLog.java index 4591894dc..c736625b5 100644 --- a/docs/dist/doc/examples/telecom/TimerLog.java +++ b/docs/dist/doc/examples/telecom/TimerLog.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,11 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package telecom; diff --git a/docs/dist/doc/examples/telecom/Timing.java b/docs/dist/doc/examples/telecom/Timing.java index f40bd0fca..29eba02ea 100644 --- a/docs/dist/doc/examples/telecom/Timing.java +++ b/docs/dist/doc/examples/telecom/Timing.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,12 +8,8 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ + package telecom; /** @@ -28,9 +23,9 @@ public aspect Timing { * Every Customer has a total connection time */ public long Customer.totalConnectTime = 0; - - public long getTotalConnectTime(Customer cust) { - return cust.totalConnectTime; + + public long getTotalConnectTime(Customer cust) { + return cust.totalConnectTime; } /** * Every connection has a timer @@ -48,7 +43,7 @@ public aspect Timing { /** * When to stop the timer */ - pointcut endTiming(Connection c): target(c) && + pointcut endTiming(Connection c): target(c) && call(void Connection.drop()); /** diff --git a/docs/dist/doc/examples/tjp/Demo.java b/docs/dist/doc/examples/tjp/Demo.java index 8b90a7a49..64d249c82 100644 --- a/docs/dist/doc/examples/tjp/Demo.java +++ b/docs/dist/doc/examples/tjp/Demo.java @@ -14,27 +14,24 @@ about the software, its performance or its conformity to any specification. package tjp; public class Demo { - static Demo d; public static void main(String[] args){ - new Demo().go(); + new Demo().go(); } void go(){ - d = new Demo(); - d.foo(1,d); - System.out.println(d.bar(new Integer(3))); + d = new Demo(); + d.foo(1,d); + System.out.println(d.bar(new Integer(3))); } void foo(int i, Object o){ - System.out.println("Demo.foo(" + i + ", " + o + ")\n"); + System.out.println("Demo.foo(" + i + ", " + o + ")\n"); } - String bar (Integer j){ - System.out.println("Demo.bar(" + j + ")\n"); - return "Demo.bar(" + j + ")"; + System.out.println("Demo.bar(" + j + ")\n"); + return "Demo.bar(" + j + ")"; } - } diff --git a/docs/dist/doc/examples/tjp/GetInfo.java b/docs/dist/doc/examples/tjp/GetInfo.java index 63f13c74e..0d38a3766 100644 --- a/docs/dist/doc/examples/tjp/GetInfo.java +++ b/docs/dist/doc/examples/tjp/GetInfo.java @@ -1,4 +1,4 @@ -/* +/* Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -24,10 +24,10 @@ aspect GetInfo { pointcut demoExecs(): within(Demo) && execution(* *(..)); Object around(): demoExecs() && !execution(* go()) && goCut() { - println("Intercepted message: " + - thisJoinPointStaticPart.getSignature().getName()); - println("in class: " + - thisJoinPointStaticPart.getSignature().getDeclaringType().getName()); + println("Intercepted message: " + + thisJoinPointStaticPart.getSignature().getName()); + println("in class: " + + thisJoinPointStaticPart.getSignature().getDeclaringType().getName()); printParameters(thisJoinPoint); println("Running original method: \n" ); Object result = proceed(); @@ -41,9 +41,9 @@ aspect GetInfo { String[] names = ((CodeSignature)jp.getSignature()).getParameterNames(); Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes(); for (int i = 0; i < args.length; i++) { - println(" " + i + ". " + names[i] + - " : " + types[i].getName() + - " = " + args[i]); + println(" " + i + ". " + names[i] + + " : " + types[i].getName() + + " = " + args[i]); } } } diff --git a/docs/dist/doc/examples/tracing/TwoDShape.java b/docs/dist/doc/examples/tracing/TwoDShape.java index 960a01b89..531b6f120 100644 --- a/docs/dist/doc/examples/tracing/TwoDShape.java +++ b/docs/dist/doc/examples/tracing/TwoDShape.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,21 +8,13 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ - package tracing; /** - * - * TwoDShape is an abstract class that defines generic functionality + * TwoDShape is an abstract class that defines generic functionality * for 2D shapes. - * */ public abstract class TwoDShape { /** diff --git a/docs/dist/doc/examples/tracing/version1/Trace.java b/docs/dist/doc/examples/tracing/version1/Trace.java index eef96df51..97b5edb3f 100644 --- a/docs/dist/doc/examples/tracing/version1/Trace.java +++ b/docs/dist/doc/examples/tracing/version1/Trace.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,11 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package tracing.version1; @@ -30,7 +24,7 @@ public class Trace { /** * There are 3 trace levels (values of TRACELEVEL): * 0 - No messages are printed - * 1 - Trace messages are printed, but there is no indentation + * 1 - Trace messages are printed, but there is no indentation * according to the call stack * 2 - Trace messages are printed, and they are indented * according to the call stack diff --git a/docs/dist/doc/examples/tracing/version1/TraceMyClasses.java b/docs/dist/doc/examples/tracing/version1/TraceMyClasses.java index b4a97ee31..736e96413 100644 --- a/docs/dist/doc/examples/tracing/version1/TraceMyClasses.java +++ b/docs/dist/doc/examples/tracing/version1/TraceMyClasses.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,18 +8,13 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package tracing.version1; /** * - * This class connects the tracing functions in the Trace class with + * This class connects the tracing functions in the Trace class with * the constructors and methods in the application classes. * */ diff --git a/docs/dist/doc/examples/tracing/version2/Trace.java b/docs/dist/doc/examples/tracing/version2/Trace.java index cd631e278..6c43d60f8 100644 --- a/docs/dist/doc/examples/tracing/version2/Trace.java +++ b/docs/dist/doc/examples/tracing/version2/Trace.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,11 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package tracing.version2; @@ -25,7 +19,7 @@ import java.io.PrintStream; * This class provides support for printing trace messages into a stream. * Trace messages are printed before and after constructors and methods * are executed. - * It defines one abstract crosscut for injecting that tracing functionality + * It defines one abstract crosscut for injecting that tracing functionality * into any application classes. * To use it, provide a subclass that concretizes the abstract crosscut. */ @@ -38,7 +32,7 @@ abstract aspect Trace { /** * There are 3 trace levels (values of TRACELEVEL): * 0 - No messages are printed - * 1 - Trace messages are printed, but there is no indentation + * 1 - Trace messages are printed, but there is no indentation * according to the call stack * 2 - Trace messages are printed, and they are indented * according to the call stack diff --git a/docs/dist/doc/examples/tracing/version2/TraceMyClasses.java b/docs/dist/doc/examples/tracing/version2/TraceMyClasses.java index a3ae99e95..d9ba21c54 100644 --- a/docs/dist/doc/examples/tracing/version2/TraceMyClasses.java +++ b/docs/dist/doc/examples/tracing/version2/TraceMyClasses.java @@ -1,5 +1,4 @@ /* - Copyright (c) Xerox Corporation 1998-2002. All rights reserved. Use and copying of this software and preparation of derivative works based @@ -9,11 +8,6 @@ laws. This software is made available AS IS, and Xerox Corporation makes no warranty about the software, its performance or its conformity to any specification. - -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| -|<--- this code is formatted to fit into 80 columns --->| - */ package tracing.version2; @@ -25,7 +19,7 @@ import tracing.ExampleMain; /** * - * This class concretizes the abstract crosscut in Trace, + * This class concretizes the abstract crosscut in Trace, * applying the trace facility to these application classes. * */ diff --git a/docs/dist/doc/quick.pdf b/docs/dist/doc/quick.pdf Binary files differindex b82afdcba..5ea889a66 100644 --- a/docs/dist/doc/quick.pdf +++ b/docs/dist/doc/quick.pdf diff --git a/docs/dist/doc/quickA4.pdf b/docs/dist/doc/quickA4.pdf Binary files differnew file mode 100644 index 000000000..514c93fae --- /dev/null +++ b/docs/dist/doc/quickA4.pdf diff --git a/docs/progGuideDB/examples.xml b/docs/progGuideDB/examples.xml index 2e6a1715d..762a4ef08 100644 --- a/docs/progGuideDB/examples.xml +++ b/docs/progGuideDB/examples.xml @@ -1,19 +1,12 @@ <chapter id="examples" xreflabel="Examples"> <title>Examples</title> - <sect1><!-- About this Chapter --> - <title>About this Chapter</title> + <sect1 id="examples-intro"> + <title>Introduction</title> - <para>This chapter consists entirely of examples of AspectJ use. - -<!-- ADD THIS IN AGAIN WHEN IT'S TRUE - The - examples have been chosen because they illustrate common AspectJ usage - patterns or techniques. Care has been taken to ensure that they also - exhibit good style, in addition to being merely syntactically and - semantically correct. ---> -</para> + <para> + This chapter consists entirely of examples of AspectJ use. + </para> <para>The examples can be grouped into four categories:</para> @@ -36,30 +29,37 @@ </sect1> +<!-- ============================== --> - <sect1> + <sect1 id="examples-howto"> <title>Obtaining, Compiling and Running the Examples</title> - <para>The examples source code is part of AspectJ's documentation - distribution which may be downloaded from <ulink - url="http://aspectj.org/dl">the AspectJ download page</ulink>.</para> + <para> + The examples source code is part of the AspectJ distribution which may be + downloaded from the AspectJ project page ( <ulink + url="http://eclipse.org/aspectj" /> ). + </para> - <para>Compiling most examples should be straightforward. Go the + <para> + Compiling most examples is straightforward. Go the <filename><replaceable>InstallDir</replaceable>/examples</filename> - directory, and look for a <filename>.lst</filename> file in one of the - example subdirectories. Use the <literal>-arglist</literal> option to - <literal>ajc</literal> to compile the example. For instance, to compile - the telecom example with billing, type </para> + directory, and look for a <filename>.lst</filename> file in one of + the example subdirectories. Use the <literal>-arglist</literal> + option to <literal>ajc</literal> to compile the example. For + instance, to compile the telecom example with billing, type + </para> <programlisting> ajc -argfile telecom/billing.lst </programlisting> - <para>To run the examples, your classpath must include the AspectJ run-time - Java archive (<literal>aspectjrt.jar</literal>). You may either set - the <literal>CLASSPATH</literal> environment variable or use the + <para> + To run the examples, your classpath must include the AspectJ run-time + Java archive (<literal>aspectjrt.jar</literal>). You may either set the + <literal>CLASSPATH</literal> environment variable or use the <literal>-classpath</literal> command line option to the Java - interpreter:</para> + interpreter: + </para> <programlisting> (In Unix use a : in the CLASSPATH) @@ -75,47 +75,51 @@ java -classpath ".;<replaceable>InstallDir</replaceable>/lib/aspectjrt.jar" tele <!-- ============================================================ --> -<!-- ============================================================ --> - - <sect1> + <sect1 id="examples-basic"> <title>Basic Techniques</title> - <para>This section presents two basic techniques of using AspectJ, one each - from the two fundamental ways of capturing crosscutting concerns: with - dynamic join points and advice, and with static introduction. Advice - changes an application's behavior. Introduction changes both an - application's behavior and its structure. </para> + <para> + This section presents two basic techniques of using AspectJ, one each + from the two fundamental ways of capturing crosscutting concerns: + with dynamic join points and advice, and with static + introduction. Advice changes an application's behavior. Introduction + changes both an application's behavior and its structure. + </para> - <para>The first example, <xref endterm="sec:JoinPointsAndtjp:title" - linkend="sec:JoinPointsAndtjp"/>, is about gathering and using - information about the join point that has triggered some advice. The - second example, <xref endterm="sec:RolesAndViews:title" - linkend="sec:RolesAndViews"/>, concerns changing an existing class - hierarchy. </para> + <para> + The first example, <xref linkend="examples-joinPoints" />, is about + gathering and using information about the join point that has + triggered some advice. The second example, <xref + linkend="examples-roles" />, concerns a crosscutting view of an + existing class hierarchy. </para> <!-- ======================================== --> - <sect2 id="sec:JoinPointsAndtjp"><!-- Join Points and thisJoinPoint --> + <sect2 id="examples-joinPoints"> <title>Join Points and <literal>thisJoinPoint</literal></title> - <titleabbrev id="sec:JoinPointsAndtjp:title">Join Points and - <literal>thisJoinPoint</literal></titleabbrev> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/tjp</filename>.)</para> + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/tjp</filename>.) + </para> - <para>A join point is some point in the - execution of a program together with a view into the execution context - when that point occurs. Join points are picked out by pointcuts. When a - join point is reached, before, after or around advice on that join - point may be run. </para> + <para> + A join point is some point in the execution of a program together + with a view into the execution context when that point occurs. Join + points are picked out by pointcuts. When a program reaches a join + point, advice on that join point may run in addition to (or instead + of) the join point itself. + </para> - <para>When dealing with pointcuts that pick out join points of specific - method calls, field gets, or the like, the advice will know exactly what - kind of join point it is executing under. It might even have access to - context given by its pointcut. Here, for example, since the only join - points reached will be calls of a certain method, we can get the target - and one of the args of the method directly. + <para> + When using a pointcut that picks out join points of a single kind + by name, typicaly the the advice will know exactly what kind of + join point it is associated with. The pointcut may even publish + context about the join point. Here, for example, since the only + join points picked out by the pointcut are calls of a certain + method, we can get the target value and one of the argument values + of the method calls directly. </para> <programlisting><![CDATA[ @@ -128,60 +132,71 @@ before(Point p, int x): target(p) } ]]></programlisting> - <para>But sometimes the join point is not so clear. For - instance, suppose a complex application is being debugged, and one - would like to know when any method in some class is being executed. - Then, the pointcut </para> + <para> + But sometimes the shape of the join point is not so clear. For + instance, suppose a complex application is being debugged, and we + want to trace when any method of some class is executed. The + pointcut + </para> <programlisting><![CDATA[ pointcut execsInProblemClass(): within(ProblemClass) && execution(* *(..)); ]]></programlisting> - <para>will select all join points where a method defined within the class - <classname>ProblemClass</classname> is being executed. But advice - executes when a particular join point is matched, and so the question, - "Which join point was matched?" naturally arises.</para> + <para> + will pick out each execution join point of every method defined + within <classname>ProblemClass</classname>. Since advice executes + at each join point picked out by the pointcut, we can reasonably + ask which join point was reached. + </para> - <para>Information about the join point that was matched is available to - advice through the special variable <varname>thisJoinPoint</varname>, - of type <ulink - url="../api/org/aspectj/lang/JoinPoint.html"><classname>org.aspectj.lang.JoinPoint</classname></ulink>. This - class provides methods that return</para> + <para> + Information about the join point that was matched is available to + advice through the special variable + <varname>thisJoinPoint</varname>, of type <ulink + url="../api/org/aspectj/lang/JoinPoint.html"><classname>org.aspectj.lang.JoinPoint</classname></ulink>. + Through this object we can access information such as</para> <itemizedlist spacing="compact"> - <listitem>the kind of join point that was matched + <listitem> + the kind of join point that was matched </listitem> - <listitem>the source location of the current join point + <listitem> + the source location of the code associated with the join point + </listitem> + <listitem> + normal, short and long string representations of the + current join point + </listitem> + <listitem> + the actual argument values of the join point + </listitem> + <listitem> + the signature of the member associated with the join point </listitem> - <listitem>normal, short and long string representations of the - current join point</listitem> - <listitem>the actual argument(s) to the method or field selected - by the current join point </listitem> - <listitem>the signature of the method or field selected by the - current join point</listitem> - <listitem>the target object</listitem> <listitem>the currently executing object</listitem> - <listitem>a reference to the static portion of the object - representing the current join point. This is also available through - the special variable <varname>thisJoinPointStaticPart</varname>.</listitem> - + <listitem>the target object</listitem> + <listitem> + an object encapsulating the static information about the join + point. This is also available through the special variable + <varname>thisJoinPointStaticPart</varname>.</listitem> </itemizedlist> <sect3> <title>The <classname>Demo</classname> class</title> - <para>The class <classname>tjp.Demo</classname> in + <para>The class <classname>tjp.Demo</classname> in <filename>tjp/Demo.java</filename> defines two methods - <literal>foo</literal> and <literal>bar</literal> with different - parameter lists and return types. Both are called, with suitable - arguments, by <classname>Demo</classname>'s <function>go</function> - method which was invoked from within its <function>main</function> - method. </para> + <literal>foo</literal> and <literal>bar</literal> with different + parameter lists and return types. Both are called, with suitable + arguments, by <classname>Demo</classname>'s + <function>go</function> method which was invoked from within its + <function>main</function> method. + </para> <programlisting><![CDATA[ public class Demo { - static Demo d; public static void main(String[] args){ @@ -198,47 +213,24 @@ public class Demo { System.out.println("Demo.foo(" + i + ", " + o + ")\n"); } - String bar (Integer j){ System.out.println("Demo.bar(" + j + ")\n"); return "Demo.bar(" + j + ")"; } - } ]]></programlisting> </sect3> <sect3> - <title>The Aspect <literal>GetInfo</literal></title> + <title>The <literal>GetInfo</literal> aspect</title> - <para>This aspect uses around advice to intercept the execution of + <para> + This aspect uses around advice to intercept the execution of methods <literal>foo</literal> and <literal>bar</literal> in - <classname>Demo</classname>, and prints out information garnered from - <literal>thisJoinPoint</literal> to the console. </para> - - <sect4> - <title>Defining the scope of a pointcut</title> - - <para>The pointcut <function>goCut</function> is defined as - <literal><![CDATA[cflow(this(Demo)) && execution(void - go())]]></literal> so that only executions made in the control - flow of <literal>Demo.go</literal> are intercepted. The control - flow from the method <literal>go</literal> includes the execution of - <literal>go</literal> itself, so the definition of the around - advice includes <literal>!execution(* go())</literal> to exclude it - from the set of executions advised. </para> - </sect4> - - <sect4> - <title>Printing the class and method name</title> - - <para>The name of the method and that method's defining class are - available as parts of the <ulink - url="../api/org/aspectj/lang/Signature.html">Signature</ulink>, - found using the method <literal>getSignature</literal> of either - <literal>thisJoinPoint</literal> or - <literal>thisJoinPointStaticPart</literal>. </para> + <classname>Demo</classname>, and prints out information garnered + from <literal>thisJoinPoint</literal> to the console. + </para> <programlisting><![CDATA[ aspect GetInfo { @@ -274,6 +266,35 @@ aspect GetInfo { } } ]]></programlisting> + + <sect4> + <title>Defining the scope of a pointcut</title> + + <para>The pointcut <function>goCut</function> is defined as + +<programlisting><![CDATA[ +cflow(this(Demo)) && execution(void go()) +]]></programlisting> + + so that only executions made in the control flow of + <literal>Demo.go</literal> are intercepted. The control flow + from the method <literal>go</literal> includes the execution of + <literal>go</literal> itself, so the definition of the around + advice includes <literal>!execution(* go())</literal> to + exclude it from the set of executions advised. </para> + </sect4> + + <sect4> + <title>Printing the class and method name</title> + + <para> + The name of the method and that method's defining class are + available as parts of the <ulink + url="../api/org/aspectj/lang/Signature.html">org.aspectj.lang.Signature</ulink> + object returned by calling <literal>getSignature()</literal> on + either <literal>thisJoinPoint</literal> or + <literal>thisJoinPointStaticPart</literal>. + </para> </sect4> <sect4> @@ -282,65 +303,76 @@ aspect GetInfo { <para> The static portions of the parameter details, the name and types of the parameters, can be accessed through the <ulink - url="../api/org/aspectj/lang/reflect/CodeSignature.html"><literal>CodeSignature</literal></ulink> + url="../api/org/aspectj/lang/reflect/CodeSignature.html"><literal>org.aspectj.lang.reflect.CodeSignature</literal></ulink> associated with the join point. All execution join points have code signatures, so the cast to <literal>CodeSignature</literal> cannot fail. </para> <para> The dynamic portions of the parameter details, the actual - values of the parameters, are accessed directly from the execution - join point object. </para> + values of the parameters, are accessed directly from the + execution join point object. + </para> </sect4> </sect3> </sect2> - <sect2 id="sec:RolesAndViews"> - <title>Roles and Views Using Introduction</title> - <titleabbrev id="sec:RolesAndViews:title">Roles and Views Using - Introduction</titleabbrev> +<!-- ============================== --> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/introduction</filename>.)</para> + <sect2 id="examples-roles"> + <title>Roles and Views</title> - <para>Like advice, pieces of introduction are members of an aspect. They - define new members that act as if they were defined on another - class. Unlike advice, introduction affects not only the behavior of the - application, but also the structural relationship between an - application's classes. </para> + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/introduction</filename>.) + </para> - <para>This is crucial: Affecting the class structure of an application at - makes these modifications available to other components of the - application.</para> + <para> + Like advice, inter-type declarations are members of an aspect. They + declare members that act as if they were defined on another class. + Unlike advice, inter-type declarations affect not only the behavior + of the application, but also the structural relationship between an + application's classes. + </para> - <para>Introduction modifies a class by adding or changing</para> - <itemizedlist spacing="compact"> - <listitem>member fields</listitem> - <listitem>member methods</listitem> - <listitem>nested classes</listitem> - </itemizedlist> + <para> + This is crucial: Publically affecting the class structure of an + application makes these modifications available to other components + of the application. + </para> - <para>and by making the class</para> + <para> + Aspects can declare inter-type - <itemizedlist spacing="compact"> - <listitem>implement interfaces</listitem> - <listitem>extend classes</listitem> - </itemizedlist> + <itemizedlist spacing="compact"> + <listitem>fields</listitem> + <listitem>methods</listitem> + <listitem>constructors</listitem> + </itemizedlist> + + and can also declare that target types + + <itemizedlist spacing="compact"> + <listitem>implement new interfaces</listitem> + <listitem>extend new classes</listitem> + </itemizedlist> + </para> <para> - This example provides three illustrations of the use of introduction to - encapsulate roles or views of a class. The class we will be introducing - into, <classname>Point</classname>, is a simple class with rectangular - and polar coordinates. Our introduction will make the class - <classname>Point</classname>, in turn, cloneable, hashable, and - comparable. These facilities are provided by introduction forms without - having to modify the class <classname>Point</classname>. - </para> + This example provides three illustrations of the use of inter-type + declarations to encapsulate roles or views of a class. The class + our aspect will be dealing with, <classname>Point</classname>, is a + simple class with rectangular and polar coordinates. Our inter-type + declarations will make the class <classname>Point</classname>, in + turn, cloneable, hashable, and comparable. These facilities are + provided by AspectJ without having to modify the code for the class + <classname>Point</classname>. + </para> <sect3> - <title>The class <classname>Point</classname></title> + <title>The <classname>Point</classname> class</title> - <para>The class <classname>Point</classname> defines geometric points + <para>The <classname>Point</classname> class defines geometric points whose interface includes polar and rectangular coordinates, plus some simple operations to relocate points. <classname>Point</classname>'s implementation has attributes for both its polar and rectangular @@ -371,35 +403,36 @@ aspect GetInfo { </sect3> <sect3> - <title>Making <classname>Point</classname>s Cloneable — The Aspect - <classname>CloneablePoint</classname></title> - - <para>This first example demonstrates the introduction of a interface - (<classname>Cloneable</classname>) and a method - (<function>clone</function>) into the class - <classname>Point</classname>. In Java, all objects inherit the method - <literal>clone</literal> from the class - <classname>Object</classname>, but an object is not cloneable unless - its class also implements the interface - <classname>Cloneable</classname>. In addition, classes frequently - have requirements over and above the simple bit-for-bit copying that - <literal>Object.clone</literal> does. In our case, we want to update - a <classname>Point</classname>'s coordinate systems before we - actually clone the <classname>Point</classname>. So we have to - override <literal>Object.clone</literal> with a new method that does - what we want. </para> - - <para>The <classname>CloneablePoint</classname> aspect uses the - <literal>declare parents</literal> form to introduce the interface - <classname>Cloneable</classname> into the class - <classname>Point</classname>. It then defines a method, - <literal>Point.clone</literal>, which overrides the method - <function>clone</function> that was inherited from - <classname>Object</classname>. <function>Point.clone</function> - updates the <classname>Point</classname>'s coordinate systems before - invoking its superclass' <function>clone</function> method.</para> - - <programlisting><![CDATA[ + <title>The <classname>CloneablePoint</classname> aspect</title> + + <para> + This first aspect is responsible for + <classname>Point</classname>'s implementation of the + <classname>Cloneable</classname> interface. It declares that + <literal>Point implements Cloneable</literal> with a + <literal>declare parents</literal> form, and also publically + declares a specialized <literal>Point</literal>'s + <literal>clone()</literal> method. In Java, all objects inherit + the method <literal>clone</literal> from the class + <classname>Object</classname>, but an object is not cloneable + unless its class also implements the interface + <classname>Cloneable</classname>. In addition, classes + frequently have requirements over and above the simple + bit-for-bit copying that <literal>Object.clone</literal> does. In + our case, we want to update a <classname>Point</classname>'s + coordinate systems before we actually clone the + <classname>Point</classname>. So our aspect makes sure that + <literal>Point</literal> overrides + <literal>Object.clone</literal> with a new method that does what + we want. + </para> + + <para> + We also define a test <literal>main</literal> method in the + aspect for convenience. + </para> + +<programlisting><![CDATA[ public aspect CloneablePoint { declare parents: Point implements Cloneable; @@ -428,34 +461,40 @@ public aspect CloneablePoint { } } ]]></programlisting> - - <para>Note that since aspects define types just as classes define - types, we can define a <function>main</function> method that is - invocable from the command line to use as a test method.</para> </sect3> <sect3> - <title>Making <classname>Point</classname>s Comparable — The - Aspect <classname>ComparablePoint</classname></title> + <title>The <classname>ComparablePoint</classname> aspect</title> - <para>This second example introduces another interface and - method into the class <classname>Point</classname>.</para> + <para> + <classname>ComparablePoint</classname> is responsible for + <literal>Point</literal>'s implementation of the + <literal>Comparable</literal> interface. </para> - <para>The interface <classname>Comparable</classname> defines the + <para> + The interface <classname>Comparable</classname> defines the single method <literal>compareTo</literal> which can be use to define a natural ordering relation among the objects of a class that - implement it. </para> - - <para>The aspect <classname>ComparablePoint</classname> introduces - implements <classname>Comparable</classname> into - <classname>Point</classname> along with a - <literal>compareTo</literal> method that can be used to compare - <classname>Point</classname>s. A <classname>Point</classname> - <literal>p1</literal> is said to be less than - another <classname>Point</classname><literal> p2</literal> if - <literal>p1</literal> is closer to the origin. </para> - - <programlisting><![CDATA[ + implement it. + </para> + + <para> + <classname>ComparablePoint</classname> uses <literal>declare + parents</literal> to declare that <literal>Point implements + Comparable</literal>, and also publically declares the + appropriate <literal>compareTo(Object)</literal> method: A + <classname>Point</classname> <literal>p1</literal> is said to be + less than another <classname>Point</classname><literal> + p2</literal> if <literal>p1</literal> is closer to the + origin. + </para> + + <para> + We also define a test <literal>main</literal> method in the + aspect for convenience. + </para> + +<programlisting><![CDATA[ public aspect ComparablePoint { declare parents: Point implements Comparable; @@ -487,18 +526,22 @@ public aspect ComparablePoint { p1.offset(1,1); System.out.println("p1 =?= p2 :" + p1.compareTo(p2)); } -}]]></programlisting> +} +]]></programlisting> </sect3> <sect3> - <title>Making <classname>Point</classname>s Hashable — The Aspect - <classname>HashablePoint</classname></title> + <title>The <classname>HashablePoint</classname> aspect</title> - <para>The third aspect overrides two previously defined methods to - give to <classname>Point</classname> the hashing behavior we - want.</para> + <para> + Our third aspect is responsible for <literal>Point</literal>'s + overriding of <literal>Object</literal>'s + <literal>equals</literal> and <literal>hashCode</literal> methods + in order to make <literal>Point</literal>s hashable. + </para> - <para>The method <literal>Object.hashCode</literal> returns an unique + <para> + The method <literal>Object.hashCode</literal> returns an unique integer, suitable for use as a hash table key. Different implementations are allowed return different integers, but must return distinct integers for distinct objects, and the same integer @@ -513,18 +556,27 @@ public aspect ComparablePoint { <literal>theta</literal> values, not just when they refer to the same object. We do this by overriding the methods <literal>equals</literal> and <literal>hashCode</literal> in the - class <classname>Point</classname>. </para> - - <para>The class <classname>HashablePoint</classname> introduces the - methods <literal>hashCode</literal> and <literal>equals</literal> - into the class <classname>Point</classname>. These methods use - <classname>Point</classname>'s rectangular coordinates to generate a - hash code and to test for equality. The <literal>x</literal> and - <literal>y</literal> coordinates are obtained using the appropriate - get methods, which ensure the rectangular coordinates are up-to-date - before returning their values. </para> - - <programlisting><![CDATA[ + class <classname>Point</classname>. + </para> + + <para> + So <classname>HashablePoint</classname> declares + <literal>Point</literal>'s <literal>hashCode</literal> and + <literal>equals</literal> methods, using + <classname>Point</classname>'s rectangular coordinates to + generate a hash code and to test for equality. The + <literal>x</literal> and <literal>y</literal> coordinates are + obtained using the appropriate get methods, which ensure the + rectangular coordinates are up-to-date before returning their + values. + </para> + + <para> + And again, we supply a <literal>main</literal> method in the + aspect for testing. + </para> + +<programlisting><![CDATA[ public aspect HashablePoint { public int Point.hashCode() { @@ -558,75 +610,68 @@ public aspect HashablePoint { } ]]></programlisting> - <para> Again, we supply a <literal>main</literal> method in the aspect - for testing. - </para> - </sect3> - </sect2> - </sect1> <!-- ============================================================ --> <!-- ============================================================ --> - <sect1> + <sect1 id="examples-development"> <title>Development Aspects</title> - <sect2> - <title>Tracing Aspects</title> + <sect2> + <title>Tracing using aspects</title> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/tracing</filename>.) + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/tracing</filename>.) </para> - <sect3> - <title>Overview</title> - - <para> - Writing a class that provides tracing functionality is easy: a couple - of functions, a boolean flag for turning tracing on and off, a choice - for an output stream, maybe some code for formatting the output---these - are all elements that <classname>Trace</classname> classes have been - known to have. <classname>Trace</classname> classes may be highly - sophisticated, too, if the task of tracing the execution of a program - demands so. + <para> + Writing a class that provides tracing functionality is easy: a + couple of functions, a boolean flag for turning tracing on and + off, a choice for an output stream, maybe some code for + formatting the output -- these are all elements that + <classname>Trace</classname> classes have been known to + have. <classname>Trace</classname> classes may be highly + sophisticated, too, if the task of tracing the execution of a + program demands it. </para> <para> - But developing the support for tracing is just one part of the effort - of inserting tracing into a program, and, most likely, not the biggest - part. The other part of the effort is calling the tracing functions at - appropriate times. In large systems, this interaction with the tracing - support can be overwhelming. Plus, tracing is one of those things that - slows the system down, so these calls should often be pulled out of the - system before the product is shipped. For these reasons, it is not - unusual for developers to write ad-hoc scripting programs that rewrite - the source code by inserting/deleting trace calls before and after the - method bodies. + But developing the support for tracing is just one part of the + effort of inserting tracing into a program, and, most likely, not + the biggest part. The other part of the effort is calling the + tracing functions at appropriate times. In large systems, this + interaction with the tracing support can be overwhelming. Plus, + tracing is one of those things that slows the system down, so + these calls should often be pulled out of the system before the + product is shipped. For these reasons, it is not unusual for + developers to write ad-hoc scripting programs that rewrite the + source code by inserting/deleting trace calls before and after + the method bodies. </para> <para> - AspectJ can be used for some of these tracing concerns in a less ad-hoc - way. Tracing can be seen as a concern that crosscuts the entire system - and as such is amenable to encapsulation in an aspect. In addition, it - is fairly independent of what the system is doing. Therefore tracing is - one of those kind of system aspects that can potentially be plugged in - and unplugged without any side-effects in the basic functionality of - the system. + AspectJ can be used for some of these tracing concerns in a less + ad-hoc way. Tracing can be seen as a concern that crosscuts the + entire system and as such is amenable to encapsulation in an + aspect. In addition, it is fairly independent of what the system + is doing. Therefore tracing is one of those kind of system + aspects that can potentially be plugged in and unplugged without + any side-effects in the basic functionality of the system. </para> - </sect3> - <sect3> - <title>An Example Application</title> + <sect3> + <title>An Example Application</title> - <para> - Throughout this example we will use a simple application that contains - only four classes. The application is about shapes. The - <classname>TwoDShape</classname> class is the root of the shape - hierarchy: - </para> + <para> + Throughout this example we will use a simple application that + contains only four classes. The application is about shapes. The + <classname>TwoDShape</classname> class is the root of the shape + hierarchy: + </para> <programlisting><![CDATA[ public abstract class TwoDShape { @@ -698,10 +743,10 @@ public class Square extends TwoDShape { <para> To run this application, compile the classes. You can do it with or - without ajc, the AspectJ compiler. If you've installed AspectJ, go to - the directory - <filename><replaceable>InstallDir</replaceable>/examples</filename> and - type: + without ajc, the AspectJ compiler. If you've installed AspectJ, go + to the directory + <filename><replaceable>InstallDir</replaceable>/examples</filename> + and type: </para> <programlisting> @@ -727,15 +772,16 @@ s1.distance(c1) = 2.23606797749979 s1.toString(): Square side = 1.0 @ (1.0, 2.0) ]]></programlisting> - </sect3> + </sect3> <sect3> <title>Tracing—Version 1</title> <para> - In a first attempt to insert tracing in this application, we will start - by writing a <classname>Trace</classname> class that is exactly what we - would write if we didn't have aspects. The implementation is in - <filename>version1/Trace.java</filename>. Its public interface is: + In a first attempt to insert tracing in this application, we will + start by writing a <classname>Trace</classname> class that is + exactly what we would write if we didn't have aspects. The + implementation is in <filename>version1/Trace.java</filename>. Its + public interface is: </para> <programlisting><![CDATA[ @@ -749,13 +795,14 @@ public class Trace { <para> If we didn't have AspectJ, we would have to insert calls to - <literal>traceEntry</literal> and <literal>traceExit</literal> in all - methods and constructors we wanted to trace, and to initialize - <literal>TRACELEVEL</literal> and the stream. If we wanted to trace all - the methods and constructors in our example, that would amount to - around 40 calls, and we would hope we had not forgotten any method. But - we can do that more consistently and reliably with the following - aspect (found in <filename>version1/TraceMyClasses.java</filename>): + <literal>traceEntry</literal> and <literal>traceExit</literal> in + all methods and constructors we wanted to trace, and to initialize + <literal>TRACELEVEL</literal> and the stream. If we wanted to trace + all the methods and constructors in our example, that would amount + to around 40 calls, and we would hope we had not forgotten any + method. But we can do that more consistently and reliably with the + following aspect (found in + <filename>version1/TraceMyClasses.java</filename>): </para> <programlisting><![CDATA[ @@ -780,22 +827,23 @@ aspect TraceMyClasses { }]]></programlisting> <para> - This aspect performs the tracing calls at appropriate times. According - to this aspect, tracing is performed at the entrance and exit of every - method and constructor defined within the shape hierarchy. + This aspect performs the tracing calls at appropriate + times. According to this aspect, tracing is performed at the + entrance and exit of every method and constructor defined within + the shape hierarchy. </para> <para> - What is printed at before and after each of the traced - join points is the signature of the method executing. Since the - signature is static information, we can get it through + What is printed at before and after each of the traced join points + is the signature of the method executing. Since the signature is + static information, we can get it through <literal>thisJoinPointStaticPart</literal>. </para> <para> To run this version of tracing, go to the directory - <filename><replaceable>InstallDir</replaceable>/examples</filename> and - type: + <filename><replaceable>InstallDir</replaceable>/examples</filename> + and type: </para> <programlisting><![CDATA[ @@ -869,13 +917,13 @@ s1.toString(): Square side = 1.0 @ (1.0, 2.0) <title>Tracing—Version 2</title> <para> - Another way to accomplish the same thing would be to write a reusable - tracing aspect that can be used not only for these application classes, - but for any class. One way to do this is to merge the tracing - functionality of <literal>Trace—version1</literal> with the - crosscutting support of - <literal>TraceMyClasses—version1</literal>. We end up with a - <literal>Trace</literal> aspect (found in + Another way to accomplish the same thing would be to write a + reusable tracing aspect that can be used not only for these + application classes, but for any class. One way to do this is to + merge the tracing functionality of + <literal>Trace—version1</literal> with the crosscutting + support of <literal>TraceMyClasses—version1</literal>. We end + up with a <literal>Trace</literal> aspect (found in <filename>version2/Trace.java</filename>) with the following public interface </para> @@ -892,8 +940,9 @@ abstract aspect Trace { ]]></programlisting> <para> - In order to use it, we need to define our own subclass that knows about - our application classes, in <filename>version2/TraceMyClasses.java</filename>: + In order to use it, we need to define our own subclass that knows + about our application classes, in + <filename>version2/TraceMyClasses.java</filename>: </para> <programlisting><![CDATA[ @@ -909,10 +958,10 @@ public aspect TraceMyClasses extends Trace { ]]></programlisting> <para> - Notice that we've simply made the pointcut <literal>classes</literal>, - that was an abstract pointcut in the super-aspect, concrete. To run - this version of tracing, go to the directory - <filename>examples</filename> and type: + Notice that we've simply made the pointcut + <literal>classes</literal>, that was an abstract pointcut in the + super-aspect, concrete. To run this version of tracing, go to the + directory <filename>examples</filename> and type: </para> <programlisting><![CDATA[ @@ -921,15 +970,15 @@ public aspect TraceMyClasses extends Trace { <para> The file tracev2.lst lists the application classes as well as this - version of the files Trace.java and TraceMyClasses.java. Running the - main method of <classname>tracing.version2.TraceMyClasses</classname> - should output exactly the same trace information as that from version - 1. + version of the files Trace.java and TraceMyClasses.java. Running + the main method of + <classname>tracing.version2.TraceMyClasses</classname> should + output exactly the same trace information as that from version 1. </para> <para> - The entire implementation of the new <classname>Trace</classname> class - is: + The entire implementation of the new <classname>Trace</classname> + class is: </para> <programlisting><![CDATA[ @@ -991,37 +1040,39 @@ abstract aspect Trace { ]]></programlisting> <para> - This version differs from version 1 in several subtle ways. The first - thing to notice is that this <classname>Trace</classname> class merges - the functional part of tracing with the crosscutting of the tracing - calls. That is, in version 1, there was a sharp separation between the - tracing support (the class <classname>Trace</classname>) and the - crosscutting usage of it (by the class - <classname>TraceMyClasses</classname>). In this version those two - things are merged. That's why the description of this class explicitly - says that "Trace messages are printed before and after constructors and - methods are," which is what we wanted in the first place. That is, the - placement of the calls, in this version, is established by the aspect - class itself, leaving less opportunity for misplacing calls.</para> - - <para> - A consequence of this is that there is no need for providing traceEntry - and traceExit as public operations of this class. You can see that they - were classified as protected. They are supposed to be internal + This version differs from version 1 in several subtle ways. The + first thing to notice is that this <classname>Trace</classname> + class merges the functional part of tracing with the crosscutting + of the tracing calls. That is, in version 1, there was a sharp + separation between the tracing support (the class + <classname>Trace</classname>) and the crosscutting usage of it (by + the class <classname>TraceMyClasses</classname>). In this version + those two things are merged. That's why the description of this + class explicitly says that "Trace messages are printed before and + after constructors and methods are," which is what we wanted in the + first place. That is, the placement of the calls, in this version, + is established by the aspect class itself, leaving less opportunity + for misplacing calls.</para> + + <para> + A consequence of this is that there is no need for providing + <literal>traceEntry</literal> and <literal>traceExit</literal> as + public operations of this class. You can see that they were + classified as protected. They are supposed to be internal implementation details of the advice. </para> <para> The key piece of this aspect is the abstract pointcut classes that - serves as the base for the definition of the pointcuts constructors and - methods. Even though <classname>classes</classname> is abstract, and - therefore no concrete classes are mentioned, we can put advice on it, - as well as on the pointcuts that are based on it. The idea is "we don't - know exactly what the pointcut will be, but when we do, here's what we - want to do with it." In some ways, abstract pointcuts are similar to - abstract methods. Abstract methods don't provide the implementation, - but you know that the concrete subclasses will, so you can invoke those - methods. + serves as the base for the definition of the pointcuts constructors + and methods. Even though <classname>classes</classname> is + abstract, and therefore no concrete classes are mentioned, we can + put advice on it, as well as on the pointcuts that are based on + it. The idea is "we don't know exactly what the pointcut will be, + but when we do, here's what we want to do with it." In some ways, + abstract pointcuts are similar to abstract methods. Abstract + methods don't provide the implementation, but you know that the + concrete subclasses will, so you can invoke those methods. </para> </sect3> </sect2> @@ -1030,64 +1081,65 @@ abstract aspect Trace { <!-- ============================================================ --> <!-- ============================================================ --> - <sect1> + <sect1 id="examples-production"> <title>Production Aspects</title> <!-- ==================== --> - <sect2><!-- A Bean Aspect --> - <title>A Bean Aspect</title> + <sect2><!-- A Bean Aspect --> + <title>A Bean Aspect</title> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/bean</filename>.) + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/bean</filename>.) </para> - <para> - This example examines an aspect that makes Point objects into a Java beans - with bound properties. </para> + <para> + This example examines an aspect that makes Point objects into + Java beans with bound properties. + </para> - <sect3> - <title>Introduction</title> <para> Java beans are reusable software components that can be visually - manipulated in a builder tool. The requirements for an object to be a - bean are few. Beans must define a no-argument constructor and must be - either <classname>Serializable</classname> or + manipulated in a builder tool. The requirements for an object to be + a bean are few. Beans must define a no-argument constructor and + must be either <classname>Serializable</classname> or <classname>Externalizable</classname>. Any properties of the object - that are to be treated as bean properties should be indicated by the - presence of appropriate <literal>get</literal> and + that are to be treated as bean properties should be indicated by + the presence of appropriate <literal>get</literal> and <literal>set</literal> methods whose names are - <literal>get</literal><emphasis>property</emphasis> and - <literal>set </literal><emphasis>property</emphasis> - where <emphasis>property</emphasis> is the name of a field in the bean + <literal>get</literal><emphasis>property</emphasis> and + <literal>set </literal><emphasis>property</emphasis> where + <emphasis>property</emphasis> is the name of a field in the bean class. Some bean properties, known as bound properties, fire events - whenever their values change so that any registered listeners (such as, - other beans) will be informed of those changes. Making a bound property - involves keeping a list of registered listeners, and creating and - dispatching event objects in methods that change the property values, - such as set<emphasis>property</emphasis> methods.</para> + whenever their values change so that any registered listeners (such + as, other beans) will be informed of those changes. Making a bound + property involves keeping a list of registered listeners, and + creating and dispatching event objects in methods that change the + property values, such as set<emphasis>property</emphasis> + methods. + </para> <para> - <classname>Point</classname> is a simple class representing points with - rectangular coordinates. <classname>Point</classname> does not know - anything about being a bean: there are set methods for + <classname>Point</classname> is a simple class representing points + with rectangular coordinates. <classname>Point</classname> does not + know anything about being a bean: there are set methods for <literal>x</literal> and <literal>y</literal> but they do not fire events, and the class is not serializable. Bound is an aspect that - makes <classname>Point</classname> a serializable class and makes its - <literal>get</literal> and <literal>set</literal> methods support the - bound property protocol. + makes <classname>Point</classname> a serializable class and makes + its <literal>get</literal> and <literal>set</literal> methods + support the bound property protocol. </para> - </sect3> <sect3> - <title>The Class <classname>Point</classname></title> + <title>The <classname>Point</classname> class</title> - <para> - The class <classname>Point</classname> is a very simple class with + <para> + The <classname>Point</classname> class is a very simple class with trivial getters and setters, and a simple vector offset method. </para> - <programlisting><![CDATA[ +<programlisting><![CDATA[ class Point { protected int x = 0; @@ -1121,52 +1173,84 @@ class Point { public String toString() { return "(" + getX() + ", " + getY() + ")" ; } -}]]></programlisting> +} +]]></programlisting> </sect3> <sect3> - <title>The Aspect <classname>BoundPoint</classname></title> + <title>The <classname>BoundPoint</classname> aspect</title> <para> - The aspect <classname>BoundPoint</classname> adds "beanness" to - <classname>Point</classname> objects. The first thing it does is - privately introduce a reference to an instance of - <classname>PropertyChangeSupport</classname> into all - <classname>Point</classname> objects. The property change - support object must be constructed with a reference to the bean for - which it is providing support, so it is initialized by passing it this, - an instance of <classname>Point</classname>. The support field is - privately introduced, so only the code in the aspect can refer to it. + The <classname>BoundPoint</classname> aspect is responsible for + <literal>Point</literal>'s "beanness". The first thing it does is + privately declare that each <literal>Point</literal> has a + <literal>support</literal> field that holds reference to an + instance of <classname>PropertyChangeSupport</classname>. + +<programlisting><![CDATA[ + private PropertyChangeSupport Point.support = new PropertyChangeSupport(this); +]]></programlisting> + + The property change support object must be constructed with a + reference to the bean for which it is providing support, so it is + initialized by passing it <literal>this</literal>, an instance of + <classname>Point</classname>. Since the <literal>support</literal> + field is private declared in the aspect, only the code in the + aspect can refer to it. </para> <para> - Methods for registering and managing listeners for property change - events are introduced into <classname>Point</classname> by the - introductions. These methods delegate the work to the - property change support object. + The aspect also declares <literal>Point</literal>'s methods for + registering and managing listeners for property change events, + which delegate the work to the property change support object: + +<programlisting><![CDATA[ + public void Point.addPropertyChangeListener(PropertyChangeListener listener){ + support.addPropertyChangeListener(listener); + } + public void Point.addPropertyChangeListener(String propertyName, + PropertyChangeListener listener){ + + support.addPropertyChangeListener(propertyName, listener); + } + public void Point.removePropertyChangeListener(String propertyName, + PropertyChangeListener listener) { + support.removePropertyChangeListener(propertyName, listener); + } + public void Point.removePropertyChangeListener(PropertyChangeListener listener) { + support.removePropertyChangeListener(listener); + } + public void Point.hasListeners(String propertyName) { + support.hasListeners(propertyName); + } +]]></programlisting> </para> <para> - The introduction also makes <classname>Point</classname> implement the - <classname>Serializable</classname> interface. Implementing - <classname>Serializable</classname> does not require any methods to be - implemented. Serialization for <classname>Point</classname> objects is - provided by the default serialization method. + The aspect is also responsible for making sure + <classname>Point</classname> implements the + <classname>Serializable</classname> interface: + +<programlisting><![CDATA[ + declare parents: Point implements Serializable; +]]></programlisting> + + Implementing this interface in Java does not require any methods to + be implemented. Serialization for <classname>Point</classname> + objects is provided by the default serialization method. </para> <para> - The pointcut <function>setters</function> names the - <literal>set</literal> methods: reception by a - <classname>Point</classname> object of any method whose name begins - with '<literal>set</literal>' and takes one parameter. The around - advice on <literal>setters()</literal> stores the values - of the <literal>X</literal> and <literal>Y</literal> properties, calls - the original <literal>set</literal> method and then fires the - appropriate property change event according to which set method was - called. Note that the call to the method proceed needs to pass along - the <literal>Point p</literal>. The rule of thumb is that context that - an around advice exposes must be passed forward to continue. + The <function>setters</function> pointcut picks out calls to the + <literal>Point</literal>'s <literal>set</literal> methods: any + method whose name begins with "<literal>set</literal>" and takes + one parameter. The around advice on <literal>setters()</literal> + stores the values of the <literal>X</literal> and + <literal>Y</literal> properties, calls the original + <literal>set</literal> method and then fires the appropriate + property change event according to which set method was + called. </para> <programlisting><![CDATA[ @@ -1176,22 +1260,18 @@ aspect BoundPoint { public void Point.addPropertyChangeListener(PropertyChangeListener listener){ support.addPropertyChangeListener(listener); } - public void Point.addPropertyChangeListener(String propertyName, PropertyChangeListener listener){ support.addPropertyChangeListener(propertyName, listener); } - public void Point.removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { support.removePropertyChangeListener(propertyName, listener); } - public void Point.removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } - public void Point.hasListeners(String propertyName) { support.hasListeners(propertyName); } @@ -1230,12 +1310,12 @@ aspect BoundPoint { <title>The Test Program</title> <para> - The test program registers itself as a property change listener to a - <literal>Point</literal> object that it creates and then performs + The test program registers itself as a property change listener to + a <literal>Point</literal> object that it creates and then performs simple manipulation of that point: calling its set methods and the - offset method. Then it serializes the point and writes it to a file and - then reads it back. The result of saving and restoring the point is that - a new point is created. + offset method. Then it serializes the point and writes it to a file + and then reads it back. The result of saving and restoring the + point is that a new point is created. </para> <programlisting><![CDATA[ @@ -1269,9 +1349,12 @@ aspect BoundPoint { ]]></programlisting> </sect3> + <sect3> <title>Compiling and Running the Example</title> - <para>To compile and run this example, go to the examples directory and type: + + <para> + To compile and run this example, go to the examples directory and type: </para> <programlisting><![CDATA[ @@ -1284,24 +1367,25 @@ java bean.Demo <!-- ==================== --> - <sect2><!-- The Subject/Observer Protocol --> - <title>The Subject/Observer Protocol</title> + <sect2> + <title>The Subject/Observer Protocol</title> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/observer</filename>.) + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/observer</filename>.) </para> - <para> - This demo illustrates how the Subject/Observer design pattern can be - coded with aspects. </para> + <para> + This demo illustrates how the Subject/Observer design pattern can be + coded with aspects. + </para> - <sect3> - <title>Overview</title> <para> - The demo consists of the following: A colored label is a renderable - object that has a color that cycles through a set of colors, and a - number that records the number of cycles it has been through. A button - is an action item that records when it is clicked. + The demo consists of the following: A colored label is a + renderable object that has a color that cycles through a set of + colors, and a number that records the number of cycles it has been + through. A button is an action item that records when it is + clicked. </para> <para> @@ -1312,22 +1396,22 @@ java bean.Demo </para> <para> - The demo is designed and implemented using the Subject/Observer design - pattern. The remainder of this example explains the classes and aspects - of this demo, and tells you how to run it. + The demo is designed and implemented using the Subject/Observer + design pattern. The remainder of this example explains the classes + and aspects of this demo, and tells you how to run it. </para> - </sect3> <sect3> <title>Generic Components</title> <para> The generic parts of the protocol are the interfaces - <classname>Subject</classname> and <classname>Observer</classname>, and - the abstract aspect <classname>SubjectObserverProtocol</classname>. The - <classname>Subject</classname> interface is simple, containing methods - to add, remove, and view <classname>Observer</classname> objects, and a - method for getting data about state changes: + <classname>Subject</classname> and <classname>Observer</classname>, + and the abstract aspect + <classname>SubjectObserverProtocol</classname>. The + <classname>Subject</classname> interface is simple, containing + methods to add, remove, and view <classname>Observer</classname> + objects, and a method for getting data about state changes: </para> <programlisting><![CDATA[ @@ -1339,9 +1423,10 @@ java bean.Demo } ]]></programlisting> - <para> The <classname>Observer</classname> interface is just as simple, - with methods to set and get <classname>Subject</classname> objects, and - a method to call when the subject gets updated. + <para> + The <classname>Observer</classname> interface is just as simple, + with methods to set and get <classname>Subject</classname> objects, + and a method to call when the subject gets updated. </para> <programlisting><![CDATA[ @@ -1354,9 +1439,9 @@ java bean.Demo <para> The <classname>SubjectObserverProtocol</classname> aspect contains - within it all of the generic parts of the protocol, namely, how to fire - the <classname>Observer</classname> objects' update methods when some - state changes in a subject. + within it all of the generic parts of the protocol, namely, how to + fire the <classname>Observer</classname> objects' update methods + when some state changes in a subject. </para> <programlisting><![CDATA[ @@ -1389,21 +1474,22 @@ java bean.Demo ]]></programlisting> <para> - Note that this aspect does three things. It define an abstract pointcut - that extending aspects can override. It defines advice that should run - after the join points of the pointcut. And it introduces state and - behavior onto the <classname>Subject</classname> and - <classname>Observer</classname> interfaces. + Note that this aspect does three things. It define an abstract + pointcut that extending aspects can override. It defines advice + that should run after the join points of the pointcut. And it + declares an inter-tpye field and two inter-type methods so that + each <literal>Observer</literal> can hold onto its <literal>Subject</literal>. </para> </sect3> <sect3> <title>Application Classes</title> - <para> <classname>Button</classname> objects extend - <classname>java.awt.Button</classname>, and all they do is make sure - the <literal>void click()</literal> method is called whenever a button - is clicked. + <para> + <classname>Button</classname> objects extend + <classname>java.awt.Button</classname>, and all they do is make + sure the <literal>void click()</literal> method is called whenever + a button is clicked. </para> <programlisting><![CDATA[ @@ -1434,6 +1520,7 @@ java bean.Demo <para> Note that this class knows nothing about being a Subject. </para> + <para> ColorLabel objects are labels that support the void colorCycle() method. Again, they know nothing about being an observer. @@ -1489,24 +1576,25 @@ aspect SubjectObserverProtocolImpl extends SubjectObserverProtocol { }]]></programlisting> <para> - It does this by introducing the appropriate interfaces onto the - <classname>Button</classname> and <classname>ColorLabel</classname> - classes, making sure the methods required by the interfaces are - implemented, and providing a definition for the + It does this by assuring that <classname>Button</classname> and + <classname>ColorLabel</classname> implement the appropriate + interfaces, declaring that they implement the methods required by + those interfaces, and providing a definition for the abstract <literal>stateChanges</literal> pointcut. Now, every time a <classname>Button</classname> is clicked, all - <classname>ColorLabel</classname> objects observing that button will - <literal>colorCycle</literal>. + <classname>ColorLabel</classname> objects observing that button + will <literal>colorCycle</literal>. </para> </sect3> <sect3> <title>Compiling and Running</title> - <para> <classname>Demo</classname> is the top class that starts this - demo. It instantiates a two buttons and three observers and links them - together as subjects and observers. So to run the demo, go to the - <filename>examples</filename> directory and type: + <para> + <classname>Demo</classname> is the top class that starts this + demo. It instantiates a two buttons and three observers and links + them together as subjects and observers. So to run the demo, go to + the <filename>examples</filename> directory and type: </para> <programlisting><![CDATA[ @@ -1520,99 +1608,108 @@ aspect SubjectObserverProtocolImpl extends SubjectObserverProtocol { <!-- ==================== --> <sect2> - <title>A Simple Telecom Simulation</title> + <title>A Simple Telecom Simulation</title> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/telecom</filename>.) + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/telecom</filename>.) </para> - <para> - This example illustrates some ways that dependent concerns can be encoded - with aspects. It uses an example system comprising a simple model of - telephone connections to which timing and billing features are added - using aspects, where the billing feature depends upon the timing feature. - </para> - - <sect3> - <title>The Application</title> - <para> - The example application is a simple simulation of a telephony system in - which customers make, accept, merge and hang-up both local and long - distance calls. The application architecture is in three layers. + This example illustrates some ways that dependent concerns can be + encoded with aspects. It uses an example system comprising a simple + model of telephone connections to which timing and billing features + are added using aspects, where the billing feature depends upon the + timing feature. </para> - <itemizedlist> - <listitem> - <para> - The basic objects provide basic functionality to simulate - customers, calls and connections (regular calls have one - connection, conference calls have more than one). - </para> - </listitem> - <listitem> - <para> - The timing feature is concerned with timing the connections and - keeping the total connection time per customer. Aspects are used to - add a timer to each connection and to manage the total time per - customer. - </para> - </listitem> + <sect3> + <title>The Application</title> + + <para> + The example application is a simple simulation of a telephony + system in which customers make, accept, merge and hang-up both + local and long distance calls. The application architecture is in + three layers. + </para> + + <itemizedlist> + <listitem> + <para> + The basic objects provide basic functionality to simulate + customers, calls and connections (regular calls have one + connection, conference calls have more than one). + </para> + </listitem> + + <listitem> + <para> + The timing feature is concerned with timing the connections + and keeping the total connection time per customer. Aspects + are used to add a timer to each connection and to manage the + total time per customer. + </para> + </listitem> + + <listitem> + <para> + The billing feature is concerned with charging customers for + the calls they make. Aspects are used to calculate a charge + per connection and, upon termination of a connection, to add + the charge to the appropriate customer's bill. The billing + aspect builds upon the timing aspect: it uses a pointcut + defined in Timing and it uses the timers that are associated + with connections. + </para> + </listitem> + </itemizedlist> - <listitem> - <para> - The billing feature is concerned with charging customers for the - calls they make. Aspects are used to calculate a charge per - connection and, upon termination of a connection, to add the charge - to the appropriate customer's bill. The billing aspect builds upon - the timing aspect: it uses a pointcut defined in Timing and it uses - the timers that are associated with connections. - </para> - </listitem> - </itemizedlist> - <para> - The simulation of system has three configurations: basic, timing and - billing. Programs for the three configurations are in classes - <classname>BasicSimulation</classname>, - <classname>TimingSimulation</classname> and - <classname>BillingSimulation</classname>. These share a common - superclass <classname>AbstractSimulation</classname>, which defines the - method run with the simulation itself and the method wait used to - simulate elapsed time. - </para> - </sect3> + <para> + The simulation of system has three configurations: basic, timing + and billing. Programs for the three configurations are in classes + <classname>BasicSimulation</classname>, + <classname>TimingSimulation</classname> and + <classname>BillingSimulation</classname>. These share a common + superclass <classname>AbstractSimulation</classname>, which + defines the method run with the simulation itself and the method + wait used to simulate elapsed time. + </para> + </sect3> - <sect3> - <title>The Basic Objects</title> - - <para> - The telecom simulation comprises the classes - <classname>Customer</classname>, <classname>Call</classname> and the - abstract class <classname>Connection</classname> with its two concrete - subclasses <classname>Local</classname> and - <classname>LongDistance</classname>. Customers have a name and a - numeric area code. They also have methods for managing calls. Simple - calls are made between one customer (the caller) and another (the - receiver), a <classname>Connection</classname> object is used to - connect them. Conference calls between more than two customers will - involve more than one connection. A customer may be involved in many - calls at one time. - <inlinemediaobject> - <imageobject> - <imagedata fileref="telecom.gif"/> - </imageobject> - </inlinemediaobject> - </para> - </sect3> + <sect3> + <title>The Basic Objects</title> - <sect3> - <title>The Class <classname>Customer</classname></title> + <para> + The telecom simulation comprises the classes + <classname>Customer</classname>, <classname>Call</classname> and + the abstract class <classname>Connection</classname> with its two + concrete subclasses <classname>Local</classname> and + <classname>LongDistance</classname>. Customers have a name and a + numeric area code. They also have methods for managing + calls. Simple calls are made between one customer (the caller) + and another (the receiver), a <classname>Connection</classname> + object is used to connect them. Conference calls between more + than two customers will involve more than one connection. A + customer may be involved in many calls at one time. - <para> - <classname>Customer</classname> has methods <literal>call</literal>, - <literal>pickup</literal>, <literal>hangup</literal> and - <literal>merge</literal> for managing calls. - </para> + <inlinemediaobject> + <imageobject> + <imagedata fileref="telecom.gif"/> + </imageobject> + </inlinemediaobject> + </para> + + </sect3> + + <sect3> + <title>The <classname>Customer</classname> class</title> + + <para> + <classname>Customer</classname> has methods + <literal>call</literal>, <literal>pickup</literal>, + <literal>hangup</literal> and <literal>merge</literal> for + managing calls. + </para> <programlisting><![CDATA[ public class Customer { @@ -1669,34 +1766,36 @@ public class Customer { } ]]></programlisting> - </sect3> + </sect3> <sect3> - <title>The Class <classname>Call</classname></title> + <title>The <classname>Call</classname> class</title> <para> - Calls are created with a caller and receiver who are customers. If the - caller and receiver have the same area code then the call can be - established with a <classname>Local</classname> connection (see below), - otherwise a <classname>LongDistance</classname> connection is required. - A call comprises a number of connections between customers. Initially - there is only the connection between the caller and receiver but - additional connections can be added if calls are merged to form - conference calls. + Calls are created with a caller and receiver who are customers. If + the caller and receiver have the same area code then the call can + be established with a <classname>Local</classname> connection (see + below), otherwise a <classname>LongDistance</classname> connection + is required. A call comprises a number of connections between + customers. Initially there is only the connection between the + caller and receiver but additional connections can be added if + calls are merged to form conference calls. </para> </sect3> <sect3> - <title>The Class <classname>Connection</classname></title> + <title>The <classname>Connection</classname> class</title> - <para>The class <classname>Connection</classname> models the physical - details of establishing a connection between customers. It does this - with a simple state machine (connections are initially + <para> + The class <classname>Connection</classname> models the physical + details of establishing a connection between customers. It does + this with a simple state machine (connections are initially <literal>PENDING</literal>, then <literal>COMPLETED</literal> and finally <literal>DROPPED</literal>). Messages are printed to the - console so that the state of connections can be observed. Connection is - an abstract class with two concrete subclasses: - <classname>Local</classname> and <classname>LongDistance</classname>. + console so that the state of connections can be + observed. Connection is an abstract class with two concrete + subclasses: <classname>Local</classname> and + <classname>LongDistance</classname>. </para> <programlisting><![CDATA[ @@ -1739,10 +1838,16 @@ public class Customer { } ]]></programlisting> - </sect3> + </sect3> <sect3> - <title>The Class Local</title> + <title>The <literal>Local</literal> and <literal>LongDistance</literal> classes</title> + + <para> + The two kinds of connections supported by our simulation are + <literal>Local</literal> and <literal>LongDistance</literal> + connections. + </para> <programlisting><![CDATA[ class Local extends Connection { @@ -1754,11 +1859,6 @@ public class Customer { } ]]></programlisting> - </sect3> - - <sect3> - <title>The Class LongDistance</title> - <programlisting><![CDATA[ class LongDistance extends Connection { LongDistance(Customer a, Customer b) { @@ -1776,8 +1876,8 @@ public class Customer { <para> The source files for the basic system are listed in the file - <filename>basic.lst</filename>. To build and run the basic system, in a - shell window, type these commands: + <filename>basic.lst</filename>. To build and run the basic system, + in a shell window, type these commands: </para> <programlisting><![CDATA[ @@ -1788,21 +1888,22 @@ java telecom.BasicSimulation </sect3> <sect3> - <title>Timing</title> + <title>The Timing aspect</title> + <para> The <classname>Timing</classname> aspect keeps track of total - connection time for each <classname>Customer</classname> by starting - and stopping a timer associated with each connection. It uses some - helper classes: + connection time for each <classname>Customer</classname> by + starting and stopping a timer associated with each connection. It + uses some helper classes: </para> <sect4> - <title>The Class <classname>Timer</classname></title> + <title>The <classname>Timer</classname> class</title> <para> - A <classname>Timer</classname> object simply records the current time - when it is started and stopped, and returns their difference when - asked for the elapsed time. The aspect + A <classname>Timer</classname> object simply records the current + time when it is started and stopped, and returns their difference + when asked for the elapsed time. The aspect <classname>TimerLog</classname> (below) can be used to cause the start and stop times to be printed to standard output. </para> @@ -1830,11 +1931,12 @@ java telecom.BasicSimulation </sect3> <sect3> - <title>The Aspect <classname>TimerLog</classname></title> + <title>The <classname>TimerLog</classname> aspect</title> <para> - The aspect <classname>TimerLog</classname> can be included in a - build to get the timer to announce when it is started and stopped. + The <classname>TimerLog</classname> aspect can be included in a + build to get the timer to announce when it is started and + stopped. </para> <programlisting><![CDATA[ @@ -1850,22 +1952,27 @@ public aspect TimerLog { } ]]></programlisting> - </sect3> + </sect3> <sect3> - <title>The Aspect <classname>Timing</classname></title> + <title>The <classname>Timing</classname> aspect</title> <para> - The aspect <classname>Timing</classname> introduces attribute - <literal>totalConnectTime</literal> into the class + The <classname>Timing</classname> aspect is declares an + inter-type field <literal>totalConnectTime</literal> for <classname>Customer</classname> to store the accumulated connection - time per <classname>Customer</classname>. It introduces attribute - timer into <classname>Connection</classname> to associate a timer - with each <classname>Connection</classname>. Two pieces of after - advice ensure that the timer is started when a connection is - completed and and stopped when it is dropped. The pointcut - <literal>endTiming</literal> is defined so that it can be used by the - <classname>Billing</classname> aspect. + time per <classname>Customer</classname>. It also declares that + each <classname>Connection</classname> object has a timer. + +<programlisting><![CDATA[ + public long Customer.totalConnectTime = 0; + private Timer Connection.timer = new Timer(); +]]></programlisting> + + Two pieces of after advice ensure that the timer is started when + a connection is completed and and stopped when it is dropped. The + pointcut <literal>endTiming</literal> is defined so that it can + be used by the <classname>Billing</classname> aspect. </para> <programlisting><![CDATA[ @@ -1893,45 +2000,42 @@ public aspect Timing { } }]]></programlisting> - </sect3> + </sect3> <sect3> - <title>Billing</title> + <title>The <literal>Billing</literal> aspect</title> <para> The Billing system adds billing functionality to the telecom application on top of timing. </para> - <sect4> - <title>The Aspect <classname>Billing</classname></title> - - <para> - The aspect <classname>Billing</classname> introduces attribute - <literal>payer</literal> into <classname>Connection</classname> - to indicate who initiated the call and therefore who is - responsible to pay for it. It also introduces method - <literal>callRate</literal> into <classname>Connection</classname> - so that local and long distance calls can be charged - differently. The call charge must be calculated after the timer is - stopped; the after advice on pointcut - <literal>Timing.endTiming</literal> does this and - <classname>Billing</classname> dominates Timing to make - sure that this advice runs after <classname>Timing's</classname> - advice on the same join point. It introduces attribute - <literal>totalCharge</literal> and its associated methods into - <classname>Customer</classname> (to manage the - customer's bill information. - </para> + <para> + The <classname>Billing</classname> aspect declares that each + <classname>Connection</classname> has a <literal>payer</literal> + inter-type field to indicate who initiated the call and therefore + who is responsible to pay for it. It also declares the inter-type + method <literal>callRate</literal> of + <classname>Connection</classname> so that local and long distance + calls can be charged differently. The call charge must be + calculated after the timer is stopped; the after advice on pointcut + <literal>Timing.endTiming</literal> does this, and + <classname>Billing</classname> is declared to be more precedent + than <classname>Timing</classname> to make sure that this advice + runs after <classname>Timing</classname>'s advice on the same join + point. Finally, it declares inter-type methods and fields for + <classname>Customer</classname> to handle the + <literal>totalCharge</literal>. + </para> <programlisting><![CDATA[ -public aspect Billing dominates Timing { - // domination required to get advice on endtiming in the right order +public aspect Billing { + // precedence required to get advice on endtiming in the right order + declare precedence: Billing, Timing; public static final long LOCAL_RATE = 3; public static final long LONG_DISTANCE_RATE = 10; - public Customer Connection.payer; public Customer getPayer(Connection conn) { return conn.payer; } @@ -1942,11 +2046,9 @@ public aspect Billing dominates Timing { public abstract long Connection.callRate(); - public long LongDistance.callRate() { return LONG_DISTANCE_RATE; } public long Local.callRate() { return LOCAL_RATE; } - after(Connection conn): Timing.endTiming(conn) { long time = Timing.aspectOf().getTimer(conn).getTime(); long rate = conn.callRate(); @@ -1954,7 +2056,6 @@ public aspect Billing dominates Timing { getPayer(conn).addCharge(cost); } - public long Customer.totalCharge = 0; public long getTotalCharge(Customer cust) { return cust.totalCharge; } @@ -1964,30 +2065,31 @@ public aspect Billing dominates Timing { } ]]></programlisting> - </sect4> </sect3> <sect3> - <title>Accessing the Introduced State</title> + <title>Accessing the inter-type state</title> <para> Both the aspects <classname>Timing</classname> and <classname>Billing</classname> contain the definition of operations that the rest of the system may want to access. For example, when - running the simulation with one or both aspects, we want to find out - how much time each customer spent on the telephone and how big their - bill is. That information is also stored in the classes, but they are - accessed through static methods of the aspects, since the state they - refer to is private to the aspect. + running the simulation with one or both aspects, we want to find + out how much time each customer spent on the telephone and how big + their bill is. That information is also stored in the classes, but + they are accessed through static methods of the aspects, since the + state they refer to is private to the aspect. </para> <para> - Take a look at the file <filename>TimingSimulation.java</filename>. The - most important method of this class is the method - <filename>report(Customer c)</filename>, which is used in the method - run of the superclass <classname>AbstractSimulation</classname>. This - method is intended to print out the status of the customer, with - respect to the <classname>Timing</classname> feature. + Take a look at the file + <filename>TimingSimulation.java</filename>. The most important + method of this class is the method + <filename>report(Customer)</filename>, which is used in the method + run of the superclass + <classname>AbstractSimulation</classname>. This method is intended + to print out the status of the customer, with respect to the + <classname>Timing</classname> feature. </para> <programlisting><![CDATA[ @@ -1996,16 +2098,16 @@ public aspect Billing dominates Timing { System.out.println(c + " spent " + t.getTotalConnectTime(c)); } ]]></programlisting> - </sect3> <sect3> <title>Compiling and Running</title> <para> - The files timing.lst and billing.lst contain file lists for the timing - and billing configurations. To build and run the application with only - the timing feature, go to the directory examples and type: + The files timing.lst and billing.lst contain file lists for the + timing and billing configurations. To build and run the application + with only the timing feature, go to the directory examples and + type: </para> <programlisting><![CDATA[ @@ -2014,8 +2116,8 @@ public aspect Billing dominates Timing { ]]></programlisting> <para> - To build and run the application with the timing and billing features, - go to the directory examples and type: + To build and run the application with the timing and billing + features, go to the directory examples and type: </para> <programlisting><![CDATA[ @@ -2029,14 +2131,15 @@ public aspect Billing dominates Timing { <title>Discussion</title> <para> - There are some explicit dependencies between the aspects Billing and - Timing: + There are some explicit dependencies between the aspects Billing + and Timing: + <itemizedlist> <listitem> <para> - Billing is declared to dominate Timing so that Billing's after - advice runs after that of Timing when they are on the same join - point. + Billing is declared more precedent than Timing so that Billing's + after advice runs after that of Timing when they are on the + same join point. </para> </listitem> @@ -2060,86 +2163,88 @@ public aspect Billing dominates Timing { <!-- ============================================================ --> <!-- ============================================================ --> - <sect1> + <sect1 id="examples-reusable"> <title>Reusable Aspects</title> <sect2> - <title>Tracing Aspects Revisited</title> + <title>Tracing using Aspects, Revisited</title> - <para>(The code for this example is in - <filename><replaceable>InstallDir</replaceable>/examples/tracing</filename>.) + <para> + (The code for this example is in + <filename><replaceable>InstallDir</replaceable>/examples/tracing</filename>.) </para> - <sect3> - <title>Tracing—Version 3</title> + <sect3> + <title>Tracing—Version 3</title> - <para> - One advantage of not exposing the methods traceEntry and traceExit as - public operations is that we can easily change their interface without - any dramatic consequences in the rest of the code. - </para> + <para> + One advantage of not exposing the methods traceEntry and + traceExit as public operations is that we can easily change their + interface without any dramatic consequences in the rest of the + code. + </para> - <para> - Consider, again, the program without AspectJ. Suppose, for example, - that at some point later the requirements for tracing change, stating - that the trace messages should always include the string representation - of the object whose methods are being traced. This can be achieved in - at least two ways. One way is keep the interface of the methods - <literal>traceEntry</literal> and <literal>traceExit</literal> as it - was before, - </para> + <para> + Consider, again, the program without AspectJ. Suppose, for + example, that at some point later the requirements for tracing + change, stating that the trace messages should always include the + string representation of the object whose methods are being + traced. This can be achieved in at least two ways. One way is + keep the interface of the methods <literal>traceEntry</literal> + and <literal>traceExit</literal> as it was before, + </para> <programlisting><![CDATA[ public static void traceEntry(String str); public static void traceExit(String str); ]]></programlisting> - <para> - In this case, the caller is responsible for ensuring that the string - representation of the object is part of the string given as argument. - So, calls must look like: - </para> + <para> + In this case, the caller is responsible for ensuring that the + string representation of the object is part of the string given + as argument. So, calls must look like: + </para> <programlisting><![CDATA[ Trace.traceEntry("Square.distance in " + toString()); ]]></programlisting> - <para> - Another way is to enforce the requirement with a second argument in the - trace operations, e.g. - </para> + <para> + Another way is to enforce the requirement with a second argument + in the trace operations, e.g. + </para> <programlisting><![CDATA[ public static void traceEntry(String str, Object obj); public static void traceExit(String str, Object obj); ]]></programlisting> - <para> - In this case, the caller is still responsible for sending the right - object, but at least there is some guarantees that some object will be - passed. The calls will look like: - </para> + <para> + In this case, the caller is still responsible for sending the + right object, but at least there is some guarantees that some + object will be passed. The calls will look like: + </para> <programlisting><![CDATA[ Trace.traceEntry("Square.distance", this); ]]></programlisting> - <para> - In either case, this change to the requirements of tracing will have - dramatic consequences in the rest of the code -- every call to the - trace operations traceEntry and traceExit must be changed! - </para> - - <para> - Here's another advantage of doing tracing with an aspect. We've already - seen that in version 2 <literal>traceEntry</literal> and - <literal>traceExit</literal> are not publicly exposed. So changing - their interfaces, or the way they are used, has only a small effect - inside the <classname>Trace</classname> class. Here's a partial view at - the implementation of <classname>Trace</classname>, version 3. The - differences with respect to version 2 are stressed in the - comments: - </para> + <para> + In either case, this change to the requirements of tracing will + have dramatic consequences in the rest of the code -- every call + to the trace operations traceEntry and traceExit must be changed! + </para> + + <para> + Here's another advantage of doing tracing with an aspect. We've + already seen that in version 2 <literal>traceEntry</literal> and + <literal>traceExit</literal> are not publicly exposed. So + changing their interfaces, or the way they are used, has only a + small effect inside the <classname>Trace</classname> + class. Here's a partial view at the implementation of + <classname>Trace</classname>, version 3. The differences with + respect to version 2 are stressed in the comments: + </para> <programlisting><![CDATA[ abstract aspect Trace { @@ -2174,13 +2279,11 @@ abstract aspect Trace { stream.println("Exiting " + str); } - private static void printIndent() { for (int i = 0; i < callDepth; i++) stream.print(" "); } - abstract pointcut myClass(Object obj); pointcut myConstructor(Object obj): myClass(obj) && execution(new(..)); @@ -2204,57 +2307,58 @@ abstract aspect Trace { ]]></programlisting> <para> - As you can see, we decided to apply the first design by preserving the - interface of the methods <literal>traceEntry</literal> and - <literal>traceExit</literal>. But it doesn't matter—we could as - easily have applied the second design (the code in the directory - <filename>examples/tracing/version3</filename> has the second design). - The point is that the effects of this change in the tracing - requirements are limited to the <classname>Trace</classname> aspect - class. + As you can see, we decided to apply the first design by preserving + the interface of the methods <literal>traceEntry</literal> and + <literal>traceExit</literal>. But it doesn't matter—we could + as easily have applied the second design (the code in the directory + <filename>examples/tracing/version3</filename> has the second + design). The point is that the effects of this change in the + tracing requirements are limited to the + <classname>Trace</classname> aspect class. </para> <para> - One implementation change worth noticing is the specification of the - pointcuts. They now expose the object. To maintain full consistency - with the behavior of version 2, we should have included tracing for - static methods, by defining another pointcut for static methods and - advising it. We leave that as an exercise. + One implementation change worth noticing is the specification of + the pointcuts. They now expose the object. To maintain full + consistency with the behavior of version 2, we should have included + tracing for static methods, by defining another pointcut for static + methods and advising it. We leave that as an exercise. </para> <para> Moreover, we had to exclude the execution join point of the method <filename>toString</filename> from the <literal>methods</literal> - pointcut. The problem here is that <literal>toString</literal> is being - called from inside the advice. Therefore if we trace it, we will end - up in an infinite recursion of calls. This is a subtle point, and one - that you must be aware when writing advice. If the advice calls back to - the objects, there is always the possibility of recursion. Keep that in - mind! + pointcut. The problem here is that <literal>toString</literal> is + being called from inside the advice. Therefore if we trace it, we + will end up in an infinite recursion of calls. This is a subtle + point, and one that you must be aware when writing advice. If the + advice calls back to the objects, there is always the possibility + of recursion. Keep that in mind! </para> <para> - In fact, esimply excluding the execution join point may not be enough, - if there are calls to other traced methods within it -- in which case, - the restriction should be + In fact, esimply excluding the execution join point may not be + enough, if there are calls to other traced methods within it -- in + which case, the restriction should be </para> - + <programlisting><![CDATA[ && !cflow(execution(String toString())) ]]></programlisting> <para> - excluding both the execution of toString methods and all join points - under that execution. + excluding both the execution of toString methods and all join + points under that execution. </para> <para> - In summary, to implement the change in the tracing requirements we had - to make a couple of changes in the implementation of the + In summary, to implement the change in the tracing requirements we + had to make a couple of changes in the implementation of the <classname>Trace</classname> aspect class, including changing the specification of the pointcuts. That's only natural. But the - implementation changes were limited to this aspect. Without aspects, we - would have to change the implementation of every application class. + implementation changes were limited to this aspect. Without + aspects, we would have to change the implementation of every + application class. </para> <para> @@ -2332,12 +2436,3 @@ s1.toString(): Square side = 1.0 @ (1.0, 2.0) </sect2> </sect1> </chapter> - -<!-- -Local variables: -compile-command: "java sax.SAXCount -v progguide.xml && java com.icl.saxon.StyleSheet -w0 progguide.xml progguide.html.xsl" -fill-column: 79 -sgml-local-ecat-files: "progguide.ced" -sgml-parent-document:("progguide.xml" "book" "chapter") -End: ---> diff --git a/docs/progGuideDB/gettingstarted.xml b/docs/progGuideDB/gettingstarted.xml index 7cd6becbd..1a2ebb445 100644 --- a/docs/progGuideDB/gettingstarted.xml +++ b/docs/progGuideDB/gettingstarted.xml @@ -1,1090 +1,1310 @@ -<chapter id="gettingstarted" xreflabel="Getting Started with AspectJ"> +<chapter id="starting" xreflabel="Getting Started with AspectJ"> <title>Getting Started with AspectJ</title> - <sect1> + <sect1 id="starting-intro"> <title>Introduction</title> - <para>Many software developers are attracted to the idea of aspect-oriented - programming - <indexterm> - <primary>aspect-oriented programming</primary> - </indexterm> - (AOP) - <indexterm> - <primary>AOP</primary> - <see> aspect-oriented programming</see> - </indexterm> - but unsure about how to begin using the technology. They - recognize the concept of crosscutting concerns, and know that they have - had problems with the implementation of such concerns in the past. But - there are many questions about how to adopt AOP into the development - process. Common questions include: + <para> + Many software developers are attracted to the idea of aspect-oriented + programming (AOP) but unsure about how to begin using the + technology. They recognize the concept of crosscutting concerns, and + know that they have had problems with the implementation of such + concerns in the past. But there are many questions about how to adopt + AOP into the development process. Common questions include: + <itemizedlist spacing="compact"> <listitem> <para>Can I use aspects in my existing code?</para> </listitem> + <listitem> - <para>What kinds of benefits can I expect to get from using aspects? + <para> + What kinds of benefits can I expect to get from using aspects? </para> </listitem> + <listitem> <para>How do I find aspects in my programs?</para> </listitem> + <listitem> <para>How steep is the learning curve for AOP?</para> </listitem> + <listitem> <para>What are the risks of using this new technology?</para> </listitem> - </itemizedlist></para> - - <para>This chapter addresses these questions in the context of AspectJ a - general-purpose aspect-oriented extension to Java. A series of abridged - examples illustrate the kinds of aspects programmers may want to - implement using AspectJ and the benefits associated with doing so. - Readers who would like to understand the examples in more detail, or who - want to learn how to program examples like these, can find the complete - examples and supporting material on the AspectJ web site(<ulink - url="http://aspectj.org/documentation/papersAndSlides/figures-cacm2001.zip"></ulink>).</para> - - <para>A significant risk in adopting any new technology is going too - far too fast. Concern about this risk causes many organizations to - be conservative about adopting new technology. To address this - issue, the examples in this chapter are grouped into three broad - categories, with aspects that are easier to adopt into existing - development projects coming earlier in this chapter. The next - section, <xref linkend="aspectjsemantics"/>, we present the core - of AspectJ's semantics, and in <xref linkend="developmentaspects"/>, - we present aspects that facilitate tasks such as debugging, - testing and performance tuning of applications. And, in the section - following, <xref linkend="productionaspects"/>, we present aspects - that implement crosscutting functionality common in Java - applications. We will defer discussing a third category of aspects, - reusable aspects until <xref linkend="aspectjlanguage"/>. </para> - - <para>These categories are informal, and this ordering is not the only way - to adopt AspectJ. Some developers may want to use a production aspect - right away. But our experience with current AspectJ users suggests that - this is one ordering that allows developers to get experience with (and - benefit from) AOP technology quickly, while also minimizing risk.</para> - </sect1> + </itemizedlist> + </para> - <sect1 id="aspectjsemantics" xreflabel="AspectJ Semantics"> - <title>AspectJ Semantics</title> + <para> + This chapter addresses these questions in the context of AspectJ: a + general-purpose aspect-oriented extension to Java. A series of + abridged examples illustrate the kinds of aspects programmers may + want to implement using AspectJ and the benefits associated with + doing so. Readers who would like to understand the examples in more + detail, or who want to learn how to program examples like these, can + find more complete examples and supporting material linked from the + AspectJ web site ( <ulink url="http://eclipse.org/aspectj" /> ). + </para> + + <para> + A significant risk in adopting any new technology is going too far + too fast. Concern about this risk causes many organizations to be + conservative about adopting new technology. To address this issue, + the examples in this chapter are grouped into three broad categories, + with aspects that are easier to adopt into existing development + projects coming earlier in this chapter. The next section, <xref + linkend="starting-aspectj"/>, we present the core of AspectJ's + features, and in <xref linkend="starting-development"/>, we present + aspects that facilitate tasks such as debugging, testing and + performance tuning of applications. And, in the section following, + <xref linkend="starting-production"/>, we present aspects that + implement crosscutting functionality common in Java applications. We + will defer discussing a third category of aspects, reusable aspects, + until <xref linkend="language"/>. + </para> + + <para> + These categories are informal, and this ordering is not the only way + to adopt AspectJ. Some developers may want to use a production aspect + right away. But our experience with current AspectJ users suggests + that this is one ordering that allows developers to get experience + with (and benefit from) AOP technology quickly, while also minimizing + risk. + </para> + </sect1> - <indexterm> - <primary>AspectJ</primary> - <secondary>semantics</secondary> - <tertiary>overview</tertiary> - </indexterm> + <sect1 id="starting-aspectj" xreflabel="Introduction to AspectJ"> + <title>Introduction to AspectJ</title> - <para>This section presents a brief introduction to the features of AspectJ + <para> + This section presents a brief introduction to the features of AspectJ used later in this chapter. These features are at the core of the - language, but this is by no means a complete overview of AspectJ.</para> + language, but this is by no means a complete overview of AspectJ. + </para> - <para>The semantics are presented using a simple figure editor system. A + <para> + The features are presented using a simple figure editor system. A <classname>Figure</classname> consists of a number of <classname>FigureElements</classname>, which can be either <classname>Point</classname>s or <classname>Line</classname>s. The - <classname>Figure</classname> class provides factory services. There is - also a <classname>Display</classname>. Most example programs later in - this chapter are based on this system as well.</para> + <classname>Figure</classname> class provides factory services. There + is also a <classname>Display</classname>. Most example programs later + in this chapter are based on this system as well. + </para> <para> <mediaobject> <imageobject> <imagedata fileref="figureUML.gif"/> </imageobject> - <caption><para>UML for the <literal>FigureEditor</literal> - example</para></caption> + <caption> + <para> + UML for the <literal>FigureEditor</literal> example + </para> + </caption> </mediaobject> </para> - <para>The motivation for AspectJ (and likewise for aspect-oriented + <para> + The motivation for AspectJ (and likewise for aspect-oriented programming) is the realization that there are issues or concerns that are not well captured by traditional programming - methodologies. Consider the problem of enforcing a security policy - in some application. By its nature, security cuts across many of - the natural units of modularity of the application. Moreover, the + methodologies. Consider the problem of enforcing a security policy in + some application. By its nature, security cuts across many of the + natural units of modularity of the application. Moreover, the security policy must be uniformly applied to any additions as the application evolves. And the security policy that is being applied - might itself evolve. Capturing concerns like a security policy in - a disciplined way is difficult and error-prone in a traditional - programming language.</para> + might itself evolve. Capturing concerns like a security policy in a + disciplined way is difficult and error-prone in a traditional + programming language. + </para> - <para>Concerns like security cut across the natural units of + <para> + Concerns like security cut across the natural units of modularity. For object-oriented programming languages, the natural - unit of modularity is the class. But in object-oriented - programming languages, crosscutting concerns are not easily turned - into classes precisely because they cut across classes, and so - these aren't reusable, they can't be refined or inherited, - they are spread through out the program in an undisciplined way, - in short, they are difficult to work with.</para> - - <para>Aspect-oriented programming is a way of modularizing - crosscutting concerns much like object-oriented programming is a - way of modularizing common concerns. AspectJ is an implementation - of aspect-oriented programming for Java.</para> - - <para>AspectJ adds to Java just one new concept, a join point, and - a few new constructs: pointcuts, advice, introduction and aspects. - Pointcuts and advice dynamically affect program flow, and - introduction statically affects a program's class - heirarchy.</para> - - <para>A <emphasis>join point</emphasis> - <indexterm><primary>join point</primary></indexterm> - is a well-defined point in the program flow. - <emphasis>Pointcuts</emphasis> - <indexterm><primary>pointcut</primary></indexterm> - select certain join points and values at those points. - <emphasis>Advice</emphasis> - <indexterm> <primary>advice</primary></indexterm> - defines code that is executed when a pointcut is reached. These - are, then, the dynamic parts of AspectJ.</para> - - <para>AspectJ also has a way of affecting a program statically. - <emphasis>Introduction</emphasis> - <indexterm><primary>introduction</primary></indexterm> - is how AspectJ modifies a program's static structure, namely, the - members of its classes and the relationship between - classes.</para> - - <para>The last new construct in AspectJ is the - <emphasis>aspect</emphasis>. - <indexterm><primary>aspect</primary></indexterm> - Aspects, are AspectJ's unit of modularity for crosscutting - concerns They are defined in terms of pointcuts, advice and - introduction.</para> - - <para>In the sections immediately following, we are first going to look at - join points and how they compose into pointcuts. Then we will look - at advice, the code which is run when a pointcut is reached. We - will see how to combine pointcuts and advice into aspects, AspectJ's - reusable, inheritable unit of modularity. Lastly, we will look at - how to modify a program's class structure with introduction. </para> + unit of modularity is the class. But in object-oriented programming + languages, crosscutting concerns are not easily turned into classes + precisely because they cut across classes, and so these aren't + reusable, they can't be refined or inherited, they are spread through + out the program in an undisciplined way, in short, they are difficult + to work with. + </para> + + <para> + Aspect-oriented programming is a way of modularizing crosscutting + concerns much like object-oriented programming is a way of + modularizing common concerns. AspectJ is an implementation of + aspect-oriented programming for Java. + </para> + + <para> + AspectJ adds to Java just one new concept, a join point -- and that's + really just a name for an existing Java concept. It adds to Java + only a few new constructs: pointcuts, advice, inter-type declarations + and aspects. Pointcuts and advice dynamically affect program flow, + inter-type declarations statically affects a program's class + heirarchy, and aspects encapsulate these new constructs. + </para> + + <para> + A <emphasis>join point</emphasis> is a well-defined point in the + program flow. A <emphasis>pointcut</emphasis> picks out certain join + points and values at those points. A piece of + <emphasis>advice</emphasis> is code that is executed when a join + point is reached. These are the dynamic parts of AspectJ. + </para> + + <para> + AspectJ also has different kinds of <emphasis>inter-type + declarations</emphasis> that allow the programmer to modify a + program's static structure, namely, the members of its classes and + the relationship between classes. + </para> + + <para> + AspectJ's <emphasis>aspect</emphasis> are the unit of modularity for + crosscutting concerns. They behave somewhat like Java classes, but + may also include pointcuts, advice and inter-type declarations. + </para> + + <para> + In the sections immediately following, we are first going to look at + join points and how they compose into pointcuts. Then we will look at + advice, the code which is run when a pointcut is reached. We will see + how to combine pointcuts and advice into aspects, AspectJ's reusable, + inheritable unit of modularity. Lastly, we will look at how to use + inter-type declarations to deal with crosscutting concerns of a + program's class structure. + </para> + +<!-- ============================== --> <sect2> <title>The Dynamic Join Point Model</title> - <indexterm> - <primary>join point</primary> - <secondary>model</secondary> - </indexterm> - - <para>A critical element in the design of any aspect-oriented - language is the join point model. The join point model provides - the common frame of reference that makes it possible to define - the dynamic structure of crosscutting concerns.</para> - - <para>This chapter describes AspectJ's dynamic join points, in - which join points are certain well-defined points in the - execution of the program. Later we will discuss introduction, - AspectJ's form for modifying a program statically. </para> - - <para>AspectJ provides for many kinds of join points, but this - chapter discusses only one of them: method call join points. A - method call join point encompasses the actions of an object - receiving a method call. It includes all the actions that - comprise a method call, starting after all arguments are - evaluated up to and including normal or abrupt return.</para> - - <para>Each method call itself is one join point. The dynamic - context of a method call may include many other join points: all - the join points that occur when executing the called method and - any methods that it calls.</para> + <para> + A critical element in the design of any aspect-oriented language is + the join point model. The join point model provides the common + frame of reference that makes it possible to define the dynamic + structure of crosscutting concerns. This chapter describes + AspectJ's dynamic join points, in which join points are certain + well-defined points in the execution of the program. + </para> + + <para> + AspectJ provides for many kinds of join points, but this chapter + discusses only one of them: method call join points. A method call + join point encompasses the actions of an object receiving a method + call. It includes all the actions that comprise a method call, + starting after all arguments are evaluated up to and including + return (either normally or by throwing an exception). + </para> + + <para> + Each method call at runtime is a different join point, even if it + comes from the same call expression in the program. Many other + join points may run while a method call join point is executing -- + all the join points that happen while executing the method body, + and in those methods called from the body. We say that these join + points execute in the <emphasis>dynamic context</emphasis> of the + original call join point. + </para> </sect2> +<!-- ============================== --> + <sect2> - <title>Pointcut Designators</title> + <title>Pointcuts</title> - <para>In AspectJ, <emphasis>pointcut designators</emphasis> (or - simply pointcuts) identify certain join points in the program - flow. For example, the pointcut</para> + <para> + In AspectJ, <emphasis>pointcuts</emphasis> pick out certain join + points in the program flow. For example, the pointcut + </para> - <programlisting format="linespecific"> -call(void Point.setX(int))</programlisting> +<programlisting format="linespecific"> +call(void Point.setX(int)) +</programlisting> - <para>identifies any call to the method <function>setX</function> - defined on <classname>Point</classname> objects. Pointcuts can be - composed using a filter composition semantics, so for example:</para> + <para> + picks out each join point that is a call to a method that has the + signature <literal>void Point.setX(int)</literal> — that is, + <classname>Point</classname>'s void <function>setX</function> + method with a single <literal>int</literal> parameter. + </para> - <programlisting format="linespecific"> + <para> + A pointcut can be built out of other pointcuts with and, or, and + not (spelled <literal>&&</literal>, <literal>||</literal>, + and <literal>!</literal>). For example: + </para> + +<programlisting format="linespecific"> call(void Point.setX(int)) || -call(void Point.setY(int))</programlisting> +call(void Point.setY(int)) +</programlisting> - <para>identifies any call to either the <function>setX</function> or - <function>setY</function> methods defined by - <classname>Point</classname>.</para> + <para> + picks out each join point that is either a call to + <function>setX</function> or a call to <function>setY</function>. + </para> - <para>Programmers can define their own pointcuts, and pointcuts - can identify join points from many different classes — in - other words, they can crosscut classes. So, for example, the - following declares a new, named pointcut:</para> + <para> + Pointcuts can identify join points from many different types + — in other words, they can crosscut types. For example, + </para> <programlisting format="linespecific"> -pointcut move(): call(void FigureElement.setXY(int,int)) || - call(void Point.setX(int)) || - call(void Point.setY(int)) || - call(void Line.setP1(Point)) || - call(void Line.setP2(Point));</programlisting> +call(void FigureElement.setXY(int,int)) || +call(void Point.setX(int)) || +call(void Point.setY(int)) || +call(void Line.setP1(Point)) || +call(void Line.setP2(Point)); +</programlisting> - <para>The effect of this declaration is that <function>move</function> is - now a pointcut that identifies any call to methods that move figure - elements. </para> + <para> + picks out each join point that is a call to one of five methods + (the first of which is an interface method, by the way). + </para> - <sect3> - <title>Property-Based Primitive Pointcuts</title> - <indexterm> - <primary>pointcut</primary> - <secondary>primitive</secondary> - </indexterm> - <indexterm> - <primary>pointcut</primary> - <secondary>name-based</secondary> - </indexterm> - <indexterm> - <primary>pointcut</primary> - <secondary>property-based</secondary> - </indexterm> - - <para>The previous pointcuts are all based on explicit enumeration - of a set of method signatures. We call this - <emphasis>name-based</emphasis> crosscutting. AspectJ also - provides mechanisms that enable specifying a pointcut in terms - of properties of methods other than their exact name. We call - this <emphasis>property-based</emphasis> crosscutting. The - simplest of these involve using wildcards in certain fields of - the method signature. For example:</para> + <para> + In our example system, this pointcut captures all the join points + when a <classname>FigureElement</classname> moves. While this is a + useful way to specify this crosscutting concern, it is a bit of a + mouthful. So AspectJ allows programmers to define their own named + pointcuts with the <literal>pointcut</literal> form. So the + following declares a new, named pointcut: + </para> <programlisting format="linespecific"> -call(void Figure.make*(..))</programlisting> +pointcut move(): + call(void FigureElement.setXY(int,int)) || + call(void Point.setX(int)) || + call(void Point.setY(int)) || + call(void Line.setP1(Point)) || + call(void Line.setP2(Point)); +</programlisting> - <para>identifies calls to any method defined on - <classname>Figure</classname>, for which the name begins with - "<function>make</function>", specifically the factory methods - <function>makePoint</function> and <function>makeLine</function>; - and</para> + <para> + and whenever this definition is visible, the programmer can simply + use <literal>move()</literal> to capture this complicated + pointcut. + </para> - <programlisting format="linespecific"> -call(public * Figure.* (..))</programlisting> + <para> + The previous pointcuts are all based on explicit enumeration of a + set of method signatures. We sometimes call this + <emphasis>name-based</emphasis> crosscutting. AspectJ also + provides mechanisms that enable specifying a pointcut in terms of + properties of methods other than their exact name. We call this + <emphasis>property-based</emphasis> crosscutting. The simplest of + these involve using wildcards in certain fields of the method + signature. For example, the pointcut + </para> - <para>identifies calls to any public method defined on - <classname>Figure</classname>.</para> +<programlisting format="linespecific"> +call(void Figure.make*(..)) +</programlisting> - <para>One very powerful primitive pointcut, - <function>cflow</function>, identifies join points based on whether - they occur in the dynamic context of another pointcut. So</para> + <para> + picks out each join point that's a call to a void method defined + on <classname>Figure</classname> whose the name begins with + "<literal>make</literal>" regardless of the method's parameters. + In our system, this picks out calls to the factory methods + <function>makePoint</function> and <function>makeLine</function>. + The pointcut + </para> - <programlisting format="linespecific"> -cflow(move())</programlisting> +<programlisting format="linespecific"> +call(public * Figure.* (..)) +</programlisting> - <para>identifies all join points that occur between receiving method - calls for the methods in <function>move</function> and returning from - those calls (either normally or by throwing an exception.) </para> + <para> + picks out each call to <classname>Figure</classname>'s public + methods. + </para> - </sect3> + <para> + But wildcards aren't the only properties AspectJ supports. + Another pointcut, <function>cflow</function>, identifies join + points based on whether they occur in the dynamic context of + other join points. So + </para> + +<programlisting format="linespecific"> +cflow(move()) +</programlisting> + + <para> + picks out each join point that occurs in the dynamic context of + the join points picked out by <literal>move()</literal>, our named + pointcut defined above. So this picks out each join points that + occurrs between when a move method is called and when it returns + (either normally or by throwing an exception). + </para> </sect2> +<!-- ============================== --> + <sect2> <title>Advice</title> - <indexterm> - <primary>advice</primary> - </indexterm> - - <para>Pointcuts are used in the definition of advice. AspectJ has - several different kinds of advice that define additional code that - should run at join points. <emphasis>Before advice</emphasis> - <indexterm> - <primary>advice</primary> - <secondary>before</secondary> - </indexterm> - runs when a join point is reached and - before the computation proceeds, i.e. it runs when computation - reaches the method call and before the actual method starts running. - <emphasis>After advice</emphasis> - <indexterm> - <primary>advice</primary> - <secondary>after</secondary> - </indexterm> - runs after the computation 'under the join point' finishes, i.e. after - the method body has run, and just before control is returned to the - caller. <emphasis>Around advice</emphasis> - <indexterm> - <primary>advice</primary> - <secondary>around</secondary> - </indexterm> - runs when the join point is reached, and has explicit control over - whether the computation under the join point is allowed to run at - all. (Around advice and some variants of after advice are not - discussed in this chapter.)</para> + + <para> + So pointcuts pick out join points. But they don't + <emphasis>do</emphasis> anything apart from picking out join + points. To actually implement crosscutting behavior, we use + advice. Advice brings together a pointcut (to pick out join + points) and a body of code (to run at each of those join points). + </para> + + <para> + AspectJ has several different kinds of advice. <emphasis>Before + advice</emphasis> runs as a join point is reached, before the + program proceeds with the join point. For example, before advice + on a method call join point runs before the actual method starts + running, just after the arguments to the method call are evaluated. + </para> + +<programlisting><![CDATA[ +before(): move() { + System.out.println("about to move"); +} +]]></programlisting> + + <para> + <emphasis>After advice</emphasis> on a particular join point runs + after the program proceeds with that join point. For example, + after advice on a method call join point runs after the method body + has run, just before before control is returned to the caller. + Because Java programs can leave a join point 'normally' or by + throwing an exception, there are three kinds of after advice: + <literal>after returning</literal>, <literal>after + throwing</literal>, and plain <literal>after</literal> (which runs + after returning <emphasis>or</emphasis> throwing, like Java's + <literal>finally</literal>). + </para> <programlisting><![CDATA[ -after(): move() { - System.out.println("A figure element moved."); +after() returning: move() { + System.out.println("just successfully moved"); } ]]></programlisting> + <para> + <emphasis>Around advice</emphasis> on a join point runs as the join + point is reached, and has explicit control over whether the program + proceeds with the join point. Around advice is not discussed in + this section. + </para> + <sect3> <title>Exposing Context in Pointcuts</title> - <para>Pointcuts can also expose part of the execution context at - their join points. Values exposed by a pointcut can be used in - the body of advice declarations. In the following code, the - pointcut exposes three values from calls to - <function>setXY</function>: the - <classname>FigureElement</classname> receiving the call, the - new value for <literal>x</literal> and the new value for - <literal>y</literal>. The advice then prints the figure - element that was moved and its new <literal>x</literal> and + <para> + Pointcuts not only pick out join points, they can also expose + part of the execution context at their join points. Values + exposed by a pointcut can be used in the body of advice + declarations. + </para> + + <para> + An advice declaration has a parameter list (like a method) that + gives names to all the pieces of context that it uses. For + example, the after advice + </para> + +<programlisting><![CDATA[ +after(FigureElement fe, int x, int y) returning: + ...SomePointcut... { + ...SomeBody... +} +]]></programlisting> + + <para> + uses three pieces of exposed context, a + <literal>FigureElement</literal> named fe, and two + <literal>int</literal>s named x and y. + </para> + + <para> + The body of the advice uses the names just like method + parameters, so + </para> + +<programlisting><![CDATA[ +after(FigureElement fe, int x, int y) returning: + ...SomePointcut... { + System.out.println(fe + " moved to (" + x + ", " + y + ")"); +} +]]></programlisting> + + <para> + The advice's pointcut publishes the values for the advice's + arguments. The three primitive pointcuts + <literal>this</literal>, <literal>target</literal> and + <literal>args</literal> are used to publish these values. So now + we can write the complete piece of advice: + </para> + +<programlisting><![CDATA[ +after(FigureElement fe, int x, int y) returning: + call(void FigureElement.setXY(int, int)) + && target(fe) + && args(x, y) { + System.out.println(fe + " moved to (" + x + ", " + y + ")"); +} +]]></programlisting> + + <para> + The pointcut exposes three values from calls to + <function>setXY</function>: the target + <classname>FigureElement</classname> -- which it publishes as + <literal>fe</literal>, so it becomes the first argument to the + after advice -- and the two int arguments -- which it publishes + as <literal>x</literal> and <literal>y</literal>, so they become + the second and third argument to the after advice. + </para> + + <para> + So the advice prints the figure element + that was moved and its new <literal>x</literal> and <literal>y</literal> coordinates after each - <classname>setXY</classname> method call.</para> + <classname>setXY</classname> method call. + </para> + + <para> + A named pointcut may have parameters like a piece of advice. + When the named pointcut is used (by advice, or in another named + pointcut), it publishes its context by name just like the + <literal>this</literal>, <literal>target</literal> and + <literal>args</literal> pointcut. So another way to write the + above advice is + </para> <programlisting><![CDATA[ pointcut setXY(FigureElement fe, int x, int y): - call(void FigureElement.setXY(int, int)) - && target(fe) - && args(x, y); + call(void FigureElement.setXY(int, int)) + && target(fe) + && args(x, y); -after(FigureElement fe, int x, int y): setXY(fe, x, y) { - System.out.println(fe + " moved to (" + x + ", " + y + ")."); +after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) { + System.out.println(fe + " moved to (" + x + ", " + y + ")."); } ]]></programlisting> </sect3> - </sect2> +<!-- ============================== --> + <sect2> - <title>Introduction</title> - <indexterm><primary>aspect</primary></indexterm> - - <para>Introduction is AspectJ's form for modifying classes and their - hierarchy. Introduction adds new members to classes and alters the - inheritance relationship between classes. Unlike advice that operates - primarily dynamically, introduction operates statically, at compilation - time. Introduction changes the declaration of classes, and it is these - changed classes that are inherited, extended or instantiated by the - rest of the program.</para> - - <para>Consider the problem of adding a new capability to some existing - classes that are already part of a class heirarchy, i.e. they already - extend a class. In Java, one creates an interface that captures - this new capability, and then adds to <emphasis>each affected - class</emphasis> a method that implements this interface.</para> - - <para>AspectJ can do better. The new capability is a crosscutting concern - because it affects multiple classes. Using AspectJ's introduction form, - we can introduce into existing classes the methods or fields that are - necessary to implement the new capability. - </para> + <title>Inter-type declarations</title> - <para>Suppose we want to have <classname>Screen</classname> objects + <para> + Inter-type declarations in AspectJ are declarations that cut across + classes and their hierarchies. They may declare members that cut + across multiple classes, or change the inheritance relationship + between classes. Unlike advice, which operates primarily + dynamically, introduction operates statically, at compile-time. + </para> + + <para> + Consider the problem of expressing a capability shared by some + existing classes that are already part of a class heirarchy, + i.e. they already extend a class. In Java, one creates an + interface that captures this new capability, and then adds to + <emphasis>each affected class</emphasis> a method that implements + this interface. + </para> + + <para> + AspectJ can express the concern in one place, by using inter-type + declarations. The aspect declares the methods and fields that are + necessary to implement the new capability, and associates the + methods and fields to the existing classes. + </para> + + <para> + Suppose we want to have <classname>Screen</classname> objects observe changes to <classname>Point</classname> objects, where <classname>Point</classname> is an existing class. We can implement - this by introducing into the class <classname>Point</classname> an - instance field, <varname>observers</varname>, that keeps track of the + this by writing an aspect declaring that the class Point + <classname>Point</classname> has an instance field, + <varname>observers</varname>, that keeps track of the <classname>Screen</classname> objects that are observing - <classname>Point</classname>s. Observers are added or removed with the - static methods <function>addObserver</function> and - <function>removeObserver</function>. The pointcut - <function>changes</function> defines what we want to observe, and the - after advice defines what we want to do when we observe a change. Note - that neither <classname>Screen</classname>'s nor - <classname>Point</classname>'s code has to be modified, and that all - the changes needed to support this new capability are local to this - aspect.</para> + <classname>Point</classname>s. + </para> - <programlisting><![CDATA[ +<programlisting><![CDATA[ aspect PointObserving { + private Vector Point.observers = new Vector(); + ... +} +]]></programlisting> - private Vector Point.observers = new Vector(); + <para> + The <literal>observers</literal> field is private, so only + <classname>PointObserving</classname> can see it. So observers are + added or removed with the static methods + <function>addObserver</function> and + <function>removeObserver</function> on the aspect. + </para> - public static void addObserver(Point p, Screen s) { - p.observers.add(s); - } +<programlisting><![CDATA[ +aspect PointObserving { + private Vector Point.observers = new Vector(); + + public static void addObserver(Point p, Screen s) { + p.observers.add(s); + } + public static void removeObserver(Point p, Screen s) { + p.observers.remove(s); + } + ... +} +]]></programlisting> - public static void removeObserver(Point p, Screen s) { - p.observers.remove(s); - } + <para> + Along with this, we can define a pointcut + <function>changes</function> that defines what we want to observe, + and the after advice defines what we want to do when we observe a + change. + </para> - pointcut changes(Point p): target(p) && call(void Point.set*(int)); +<programlisting><![CDATA[ +aspect PointObserving { + private Vector Point.observers = new Vector(); + + public static void addObserver(Point p, Screen s) { + p.observers.add(s); + } + public static void removeObserver(Point p, Screen s) { + p.observers.remove(s); + } + + pointcut changes(Point p): target(p) && call(void Point.set*(int)); + + after(Point p): changes(p) { + Iterator iter = p.observers.iterator(); + while ( iter.hasNext() ) { + updateObserver(p, (Screen)iter.next()); + } + } + + static void updateObserver(Point p, Screen s) { + s.display(p); + } +} +]]></programlisting> - after(Point p): changes(p) { - Iterator iter = p.observers.iterator(); - while ( iter.hasNext() ) { - updateObserver(p, (Screen)iter.next()); - } - } + <para> + Note that neither <classname>Screen</classname>'s nor + <classname>Point</classname>'s code has to be modified, and that + all the changes needed to support this new capability are local to + this aspect. + </para> - static void updateObserver(Point p, Screen s) { - s.display(p); - } -}]]></programlisting> </sect2> +<!-- ============================== --> + <sect2> - <title>Aspect Declarations</title> - - <para>An <emphasis>aspect</emphasis> - <indexterm><primary>aspect</primary></indexterm> is a modular unit of - crosscutting implementation. It is defined very much like a class, - and can have methods, fields, and initializers. The crosscutting - implementation is provided in terms of pointcuts, advice and - introductions. Only aspects may include advice, so while AspectJ - may define crosscutting effects, the declaration of those effects is - localized.</para> - - <para>The next three sections present the use of aspects in - increasingly sophisticated ways. Development aspects are easily removed - from production builds. Production aspects are intended to be used in - both development and in production, but tend to affect only a few - classes. Finally, reusable aspects require the most experience to get - right.</para> + <title>Aspects</title> - </sect2> + <para> + Aspects wrap up pointcuts, advice, and inter-type declarations in a + a modular unit of crosscutting implementation. It is defined very + much like a class, and can have methods, fields, and initializers + in addition to the crosscutting members. Because only aspects may + include these crosscutting members, the declaration of these + effects is localized. + </para> + + <para> + Like classes, aspects may be instantiated, but AspectJ controls how + that instantiation happens -- so you can't use Java's + <literal>new</literal> form to build new aspect instances. By + default, each aspect is a singleton, so one aspect instance is + created. This means that advice may use non-static fields of the + aspect, if it needs to keep state around: + </para> + +<programlisting><![CDATA[ +aspect Logging { + OutputStream logStream = System.err; + + before(): move() { + logStream.println("about to move"); + } +} +]]></programlisting> + + <para> + Aspects may also have more complicated rules for instantiation, but + these will be described in a later chapter. + </para> + </sect2> </sect1> - <sect1 id="developmentaspects" xreflabel="Development Aspects"> +<!-- ============================== --> + + <sect1 id="starting-development" xreflabel="Development Aspects"> <title>Development Aspects</title> - <indexterm> - <primary>aspect</primary> - <secondary>development</secondary> - </indexterm> - <para>This section presents examples of aspects that can be used during + <para> + The next two sections present the use of aspects in increasingly + sophisticated ways. Development aspects are easily removed from + production builds. Production aspects are intended to be used in + both development and in production, but tend to affect only a few + classes. + </para> + + <para> + This section presents examples of aspects that can be used during development of Java applications. These aspects facilitate debugging, testing and performance tuning work. The aspects define behavior that ranges from simple tracing, to profiling, to testing of internal - consistency within the application. Using AspectJ makes it possible to - cleanly modularize this kind of functionality, thereby making it possible - to easily enable and disable the functionality when desired. </para> + consistency within the application. Using AspectJ makes it possible + to cleanly modularize this kind of functionality, thereby making it + possible to easily enable and disable the functionality when desired. + </para> <sect2> - <title>Tracing, Logging, and Profiling</title> - <indexterm> - <primary>tracing</primary> - </indexterm> - <indexterm> - <primary>logging</primary> - </indexterm> - <indexterm> - <primary>profiling</primary> - </indexterm> - - <para>This first example shows how to increase the visibility of the + <title>Tracing</title> + + <para> + This first example shows how to increase the visibility of the internal workings of a program. It is a simple tracing aspect that prints a message at specified method calls. In our figure editor example, one such aspect might simply trace whenever points are - drawn.</para> + drawn. + </para> <programlisting><![CDATA[ aspect SimpleTracing { - pointcut tracedCall(): - call(void FigureElement.draw(GraphicsContext)); + pointcut tracedCall(): + call(void FigureElement.draw(GraphicsContext)); - before(): tracedCall() { - System.out.println("Entering: " + thisJoinPoint); - } + before(): tracedCall() { + System.out.println("Entering: " + thisJoinPoint); + } } ]]></programlisting> - <para>This code makes use of the <literal>thisJoinPoint</literal> special - variable. Within all advice bodies this variable is bound to an object - that describes the current join point. The effect of this code - is to print a line like the following every time a figure element - receives a <function>draw</function> method call:</para> + <para> + This code makes use of the <literal>thisJoinPoint</literal> special + variable. Within all advice bodies this variable is bound to an + object that describes the current join point. The effect of this + code is to print a line like the following every time a figure + element receives a <function>draw</function> method call: + </para> <programlisting><![CDATA[ Entering: call(void FigureElement.draw(GraphicsContext)) ]]></programlisting> - <para>To understand the benefit of coding this with AspectJ consider - changing the set of method calls that are traced. With AspectJ, this - just requires editing the definition of the + <para> + To understand the benefit of coding this with AspectJ consider + changing the set of method calls that are traced. With AspectJ, + this just requires editing the definition of the <function>tracedCalls</function> pointcut and recompiling. The - individual methods that are traced do not need to be edited.</para> + individual methods that are traced do not need to be edited. + </para> - <para>When debugging, programmers often invest considerable effort in + <para> + When debugging, programmers often invest considerable effort in figuring out a good set of trace points to use when looking for a - particular kind of problem. When debugging is complete or appears to - be complete it is frustrating to have to lose that investment by + particular kind of problem. When debugging is complete or appears + to be complete it is frustrating to have to lose that investment by deleting trace statements from the code. The alternative of just commenting them out makes the code look bad, and can cause trace statements for one kind of debugging to get confused with trace - statements for another kind of debugging.</para> + statements for another kind of debugging. + </para> - <para>With AspectJ it is easy to both preserve the work of designing a - good set of trace points and disable the tracing when it isn t being - used. This is done by writing an aspect specifically for that tracing - mode, and removing that aspect from the compilation when it is not - needed.</para> + <para> + With AspectJ it is easy to both preserve the work of designing a + good set of trace points and disable the tracing when it isn t + being used. This is done by writing an aspect specifically for that + tracing mode, and removing that aspect from the compilation when it + is not needed. + </para> - <para>This ability to concisely implement and reuse debugging - configurations that have proven useful in the past is a direct result - of AspectJ modularizing a crosscutting design element the set of - methods that are appropriate to trace when looking for a given kind of - information.</para> + <para> + This ability to concisely implement and reuse debugging + configurations that have proven useful in the past is a direct + result of AspectJ modularizing a crosscutting design element the + set of methods that are appropriate to trace when looking for a + given kind of information. + </para> + </sect2> - <sect3> - <title>Profiling and Logging</title> - <indexterm><primary>logging</primary></indexterm> - <indexterm><primary>profiling</primary></indexterm> - - <para> Our second example shows you how to do some very specific - profiling. Although many sophisticated profiling tools are available, - and these can gather a variety of information and display the results - in useful ways, you may sometimes want to profile or log some very - specific behavior. In these cases, it is often possible to write a - simple aspect similar to the ones above to do the job.</para> - - <para>For example, the following aspect<footnote> - <para>Since aspects are by default singleton aspects, i.e. there is - only one instance of the aspect, fields in a singleton aspect are - similar to static fields in class.</para></footnote> will count - the number of calls to the <function>rotate</function> method on a - <classname>Line</classname> and the number of calls to the - <function>set*</function> methods of a <classname>Point</classname> - that happen within the control flow of those calls to - <function>rotate</function>:</para> + <sect2> + <title>Profiling and Logging</title> + + <para> + Our second example shows you how to do some very specific + profiling. Although many sophisticated profiling tools are + available, and these can gather a variety of information and + display the results in useful ways, you may sometimes want to + profile or log some very specific behavior. In these cases, it is + often possible to write a simple aspect similar to the ones above + to do the job. + </para> + + <para> + For example, the following aspect counts the number of calls to the + <function>rotate</function> method on a <classname>Line</classname> + and the number of calls to the <function>set*</function> methods of + a <classname>Point</classname> that happen within the control flow + of those calls to <function>rotate</function>: + </para> <programlisting><![CDATA[ aspect SetsInRotateCounting { - int rotateCount = 0; - int setCount = 0; - - before(): call(void Line.rotate(double)) { - rotateCount++; - } - - before(): call(void Point.set*(int)) && - cflow(call(void Line.rotate(double))) { - setCount++; - } -}]]></programlisting> - - <para>Aspects have an advantage over standard profiling or logging - tools because they can be programmed to ask very specific and complex - questions like, "How many times is the <function>rotate</function> - method defined on <classname>Line</classname> objects called, and how - many times are methods defined on <classname>Point</classname> - objects whose name begins with `<function>set</function>' called in - fulfilling those rotate calls"?</para> + int rotateCount = 0; + int setCount = 0; - </sect3> + before(): call(void Line.rotate(double)) { + rotateCount++; + } + + before(): call(void Point.set*(int)) + && cflow(call(void Line.rotate(double))) { + setCount++; + } +} +]]></programlisting> + + <para> + In effect, this aspect allows the programmer to ask very specific + questions like + + <blockquote> + How many times is the <function>rotate</function> + method defined on <classname>Line</classname> objects called? + </blockquote> + + and + + <blockquote> + How many times are methods defined on + <classname>Point</classname> objects whose name begins with + "<function>set</function>" called in fulfilling those rotate + calls? + </blockquote> + + questions it may be difficult to express using standard + profiling or logging tools. + </para> </sect2> +<!-- ============================== --> + <sect2> <title>Pre- and Post-Conditions</title> - <indexterm><primary>pre-condition</primary></indexterm> - <indexterm><primary>post-condition</primary></indexterm> - <indexterm><primary>assertion</primary></indexterm> - - <para>Many programmers use the "Design by Contract" style popularized by + <para> + Many programmers use the "Design by Contract" style popularized by Bertand Meyer in <citetitle>Object-Oriented Software Construction, - 2/e</citetitle>. In this style of programming, explicit + 2/e</citetitle>. In this style of programming, explicit pre-conditions test that callers of a method call it properly and - explicit post-conditions test that methods properly do the work they - are supposed to.</para> + explicit post-conditions test that methods properly do the work + they are supposed to. + </para> <para> - AspectJ makes it possible to implement pre- and post-condition testing - in modular form. For example, this code </para> + AspectJ makes it possible to implement pre- and post-condition + testing in modular form. For example, this code + </para> - <programlisting><![CDATA[ +<programlisting><![CDATA[ aspect PointBoundsChecking { - pointcut setX(int x): - (call(void FigureElement.setXY(int, int)) && args(x, *)) - || (call(void Point.setX(int)) && args(x)); + pointcut setX(int x): + (call(void FigureElement.setXY(int, int)) && args(x, *)) + || (call(void Point.setX(int)) && args(x)); - pointcut setY(int y): - (call(void FigureElement.setXY(int, int)) && args(*, y)) - || (call(void Point.setY(int)) && args(y)); + pointcut setY(int y): + (call(void FigureElement.setXY(int, int)) && args(*, y)) + || (call(void Point.setY(int)) && args(y)); - before(int x): setX(x) { - if ( x < MIN_X || x > MAX_X ) - throw new IllegalArgumentException("x is out of bounds."); - } + before(int x): setX(x) { + if ( x < MIN_X || x > MAX_X ) + throw new IllegalArgumentException("x is out of bounds."); + } - before(int y): setY(y) { - if ( y < MIN_Y || y > MAX_Y ) - throw new IllegalArgumentException("y is out of bounds."); - } + before(int y): setY(y) { + if ( y < MIN_Y || y > MAX_Y ) + throw new IllegalArgumentException("y is out of bounds."); + } } ]]></programlisting> - <para>implements the bounds checking aspect of pre-condition testing for - operations that move points. Notice that the <function>setX</function> - pointcut refers to all the operations that can set a point's - <literal>x</literal> coordinate; this includes the - <function>setX</function> method, as well as half of the - <function>setXY</function> method. In this sense the + <para> + implements the bounds checking aspect of pre-condition testing for + operations that move points. Notice that the + <function>setX</function> pointcut refers to all the operations + that can set a Point's <literal>x</literal> coordinate; this + includes the <function>setX</function> method, as well as half of + the <function>setXY</function> method. In this sense the <function>setX</function> pointcut can be seen as involving very - fine-grained crosscutting—it names the the + fine-grained crosscutting — it names the the <function>setX</function> method and half of the - <function>setXY</function> method.</para> + <function>setXY</function> method. + </para> - <para>Even though pre- and post-condition testing aspects can often be - used only during testing, in some cases developers may wish to include - them in the production build as well. Again, because AspectJ makes it - possible to modularize these crosscutting concerns cleanly, it gives - developers good control over this decision.</para> + <para> + Even though pre- and post-condition testing aspects can often be + used only during testing, in some cases developers may wish to + include them in the production build as well. Again, because + AspectJ makes it possible to modularize these crosscutting concerns + cleanly, it gives developers good control over this decision. + </para> </sect2> +<!-- ============================== --> + <sect2> <title>Contract Enforcement</title> - <indexterm><primary>contract enforcement</primary></indexterm> -<!-- <remark>What is a compelling example of runtime contract enforcement that has --> -<!-- croscutting concerns so that Java 1.4-based assertions won't be --> -<!-- sufficient? --> -<!-- </remark> --> <para> The property-based crosscutting mechanisms can be very useful in defining more sophisticated contract enforcement. One very powerful - use of these mechanisms is to identify method calls that, in a correct - program, should not exist. For example, the following aspect enforces - the constraint that only the well-known factory methods can add an - element to the registry of figure elements. Enforcing this constraint - ensures that no figure element is added to the registry more than - once.</para> + use of these mechanisms is to identify method calls that, in a + correct program, should not exist. For example, the following + aspect enforces the constraint that only the well-known factory + methods can add an element to the registry of figure + elements. Enforcing this constraint ensures that no figure element + is added to the registry more than once. + </para> <programlisting><![CDATA[ static aspect RegistrationProtection { - pointcut register(): call(void Registry.register(FigureElement)); + pointcut register(): call(void Registry.register(FigureElement)); - pointcut canRegister(): withincode(static * FigureElement.make*(..)); + pointcut canRegister(): withincode(static * FigureElement.make*(..)); - before(): register() && !canRegister() { - throw new IllegalAccessException("Illegal call " + thisJoinPoint); - } + before(): register() && !canRegister() { + throw new IllegalAccessException("Illegal call " + thisJoinPoint); + } } ]]></programlisting> - <para>This aspect uses the withincode primitive pointcut to denote all + <para> + This aspect uses the withincode primitive pointcut to denote all join points that occur within the body of the factory methods on - <classname>FigureElement</classname> (the methods with names that begin - with "<literal>make</literal>"). This is a property-based pointcut - because it identifies join points based not on their signature, but - rather on the property that they occur specifically within the code of - another method. The before advice declaration effectively says signal - an error for any calls to register that are not within the factory - methods.</para> + <classname>FigureElement</classname> (the methods with names that + begin with "<literal>make</literal>"). This is a property-based + pointcut because it identifies join points based not on their + signature, but rather on the property that they occur specifically + within the code of another method. The before advice declaration + effectively says signal an error for any calls to register that are + not within the factory methods. + </para> + + <para> + This advice throws a runtime exception at certain join points, but + AspectJ can do better. Using the <literal>declare error</literal> + form, we can have the <emphasis>compiler</emphasis> signal the + error. + </para> +<programlisting><![CDATA[ +static aspect RegistrationProtection { + + pointcut register(): call(void Registry.register(FigureElement)); + pointcut canRegister(): withincode(static * FigureElement.make*(..)); + + declare error: register() && !canRegister(): "Illegal call" +} +]]></programlisting> + + <para> + When using this aspect, it is impossible for the compiler to + compile programs with these illegal calls. This early detection is + not always possible. In this case, since we depend only on static + information (the <literal>withincode</literal> pointcut picks out + join points totally based on their code, and the + <literal>call</literal> pointcut here picks out join points + statically). Other enforcement, such as the precondition + enforcement, above, does require dynamic information such as the + runtime value of parameters. + </para> </sect2> - <sect2 id="configurationmanagement" xreflabel="Configuration Management"> +<!-- ============================== --> + + <sect2> <title>Configuration Management</title> - <indexterm> - <primary>configuration management</primary> - </indexterm> - <para>Configuration management for aspects can be handled using a variety - of make-file like techniques. To work with optional aspects, the + <para> + Configuration management for aspects can be handled using a variety + of make-file like techniques. To work with optional aspects, the programmer can simply define their make files to either include the - aspect in the call to the AspectJ compiler or not, as desired.</para> + aspect in the call to the AspectJ compiler or not, as desired. + </para> - <para>Developers who want to be certain that no aspects are included in - the production build can do so by configuring their make files so that - they use a traditional Java compiler for production builds. To make it - easy to write such make files, the AspectJ compiler has a command-line - interface that is consistent with ordinary Java compilers.</para> + <para> + Developers who want to be certain that no aspects are included in + the production build can do so by configuring their make files so + that they use a traditional Java compiler for production builds. To + make it easy to write such make files, the AspectJ compiler has a + command-line interface that is consistent with ordinary Java + compilers. + </para> </sect2> - </sect1> - <sect1 id="productionaspects" xreflabel="Production Aspects"> +<!-- ============================== --> + + <sect1 id="starting-production" xreflabel="Production Aspects"> <title>Production Aspects</title> - <indexterm> - <primary>aspect</primary> - <secondary>production</secondary> - </indexterm> - - <para>This section presents examples of aspects that are inherently - intended to be included in the production builds of an application. - Production aspects tend to add functionality to an application rather - than merely adding more visibility of the internals of a program. Again, - we begin with name-based aspects and follow with property-based aspects. - Name-based production aspects tend to affect only a small number of - methods. For this reason, they are a good next step for projects - adopting AspectJ. But even though they tend to be small and simple, they - can often have a significant effect in terms of making the program easier - to understand and maintain.</para> + + <para> + This section presents examples of aspects that are inherently + intended to be included in the production builds of an application. + Production aspects tend to add functionality to an application + rather than merely adding more visibility of the internals of a + program. Again, we begin with name-based aspects and follow with + property-based aspects. Name-based production aspects tend to + affect only a small number of methods. For this reason, they are a + good next step for projects adopting AspectJ. But even though they + tend to be small and simple, they can often have a significant + effect in terms of making the program easier to understand and + maintain. + </para> <sect2> <title>Change Monitoring</title> - <indexterm><primary>change monitoring</primary></indexterm> - <para>The first example production aspect shows how one might implement + <para> + The first example production aspect shows how one might implement some simple functionality where it is problematic to try and do it - explicitly. It supports the code that refreshes the display. The role - of the aspect is to maintain a dirty bit indicating whether or not an - object has moved since the last time the display was refreshed.</para> - - <para>Implementing this functionality as an aspect is straightforward. - The <function>testAndClear</function> method is called by the display - code to find out whether a figure element has moved recently. This - method returns the current state of the dirty flag and resets it to - false. The pointcut <function>move</function> captures all the method - calls that can move a figure element. The after advice on - <function>move</function> sets the dirty flag whenever an object - moves.</para> + explicitly. It supports the code that refreshes the display. The + role of the aspect is to maintain a dirty bit indicating whether or + not an object has moved since the last time the display was + refreshed. + </para> + + <para> + Implementing this functionality as an aspect is straightforward. + The <function>testAndClear</function> method is called by the + display code to find out whether a figure element has moved + recently. This method returns the current state of the dirty flag + and resets it to false. The pointcut <function>move</function> + captures all the method calls that can move a figure element. The + after advice on <function>move</function> sets the dirty flag + whenever an object moves. + </para> <programlisting><![CDATA[ aspect MoveTracking { - - private static boolean dirty = false; - - public static boolean testAndClear() { - boolean result = dirty; - dirty = false; - return result; - } - - pointcut move(): call(void FigureElement.setXY(int, int)) || - call(void Line.setP1(Point)) || - call(void Line.setP2(Point)) || - call(void Point.setX(int)) || - call(void Point.setY(int)); - - after() returning: move() { - dirty = true; - } + private static boolean dirty = false; + + public static boolean testAndClear() { + boolean result = dirty; + dirty = false; + return result; + } + + pointcut move(): + call(void FigureElement.setXY(int, int)) || + call(void Line.setP1(Point)) || + call(void Line.setP2(Point)) || + call(void Point.setX(int)) || + call(void Point.setY(int)); + + after() returning: move() { + dirty = true; + } } ]]></programlisting> - <para>Even this simple example serves to illustrate some of the important + <para> + Even this simple example serves to illustrate some of the important benefits of using AspectJ in production code. Consider implementing - this functionality with ordinary Java: there would likely be a helper - class that contained the <literal>dirty</literal> flag, the + this functionality with ordinary Java: there would likely be a + helper class that contained the <literal>dirty</literal> flag, the <function>testAndClear</function> method, as well as a <function>setFlag</function> method. Each of the methods that could move a figure element would include a call to the - <function>setFlag</function> method. Those calls, or rather the concept - that those calls should happen at each move operation, are the - crosscutting concern in this case. </para> + <function>setFlag</function> method. Those calls, or rather the + concept that those calls should happen at each move operation, are + the crosscutting concern in this case. + </para> - <para>The AspectJ implementation has several advantages over the standard - implementation:</para> + <para> + The AspectJ implementation has several advantages over the standard + implementation: + </para> - <para><emphasis>The structure of the crosscutting concern is captured - explicitly.</emphasis> The moves pointcut clearly states all the + <para> + <emphasis>The structure of the crosscutting concern is captured + explicitly.</emphasis> The moves pointcut clearly states all the methods involved, so the programmer reading the code sees not just - individual calls to <literal>setFlag</literal>, but instead sees the - real structure of the code. The IDE support included with AspectJ - automatically reminds the programmer that this aspect advises each of - the methods involved. The IDE support also provides commands to jump - to the advice from the method and vice-versa.</para> - - <para><emphasis>Evolution is easier.</emphasis> If, for example, the - aspect needs to be revised to record not just that some figure element - moved, but rather to record exactly which figure elements moved, the - change would be entirely local to the aspect. The pointcut would be - updated to expose the object being moved, and the advice would be - updated to record that object. The paper <citetitle>An Overview of - AspectJ</citetitle>, presented at ECOOP 2001, presents a detailed - discussion of various ways this aspect could be expected to - evolve.)</para> - - <para><emphasis>The functionality is easy to plug in and out.</emphasis> + individual calls to <literal>setFlag</literal>, but instead sees + the real structure of the code. The IDE support included with + AspectJ automatically reminds the programmer that this aspect + advises each of the methods involved. The IDE support also + provides commands to jump to the advice from the method and + vice-versa. + </para> + + <para> + <emphasis>Evolution is easier.</emphasis> If, for example, the + aspect needs to be revised to record not just that some figure + element moved, but rather to record exactly which figure elements + moved, the change would be entirely local to the aspect. The + pointcut would be updated to expose the object being moved, and the + advice would be updated to record that object. The paper + <citetitle>An Overview of AspectJ</citetitle> (available linked off + of the AspectJ web site -- <ulink + url="http://eclipse.org/aspectj" />), presented at ECOOP + 2001, presents a detailed discussion of various ways this aspect + could be expected to evolve. + </para> + + <para> + <emphasis>The functionality is easy to plug in and out.</emphasis> Just as with development aspects, production aspects may need to be - removed from the system, either because the functionality is no longer - needed at all, or because it is not needed in certain configurations of - a system. Because the functionality is modularized in a single aspect - this is easy to do.</para> - - <para><emphasis>The implementation is more stable.</emphasis> If, for - example, the programmer adds a subclass of <classname>Line</classname> - that overrides the existing methods, this advice in this aspect will - still apply. In the ordinary Java implementation the programmer would - have to remember to add the call to <function>setFlag</function> in the - new overriding method. This benefit is often even more compelling for + removed from the system, either because the functionality is no + longer needed at all, or because it is not needed in certain + configurations of a system. Because the functionality is + modularized in a single aspect this is easy to do. + </para> + + <para> + <emphasis>The implementation is more stable.</emphasis> If, for + example, the programmer adds a subclass of + <classname>Line</classname> that overrides the existing methods, + this advice in this aspect will still apply. In the ordinary Java + implementation the programmer would have to remember to add the + call to <function>setFlag</function> in the new overriding + method. This benefit is often even more compelling for property-based aspects (see the section <xref - linkend="consistentbehavior"/>). </para> + linkend="starting-production-consistentBehavior"/>). + </para> </sect2> +<!-- ============================== --> + <sect2> <title>Context Passing</title> - <para>The crosscutting structure of context passing can be a significant + <para> + The crosscutting structure of context passing can be a significant source of complexity in Java programs. Consider implementing - functionality that would allow a client of the figure editor (a program - client rather than a human) to set the color of any figure elements - that are created. Typically this requires passing a color, or a color - factory, from the client, down through the calls that lead to the - figure element factory. All programmers are familiar with the - inconvenience of adding a first argument to a number of methods just to - pass this kind of context information.</para> - - <para>Using AspectJ, this kind of context passing can be implemented in a - modular way. The following code adds after advice that runs only when - the factory methods of <classname>Figure</classname> are called in the - control flow of a method on a - <classname>ColorControllingClient</classname>. </para> + functionality that would allow a client of the figure editor (a + program client rather than a human) to set the color of any figure + elements that are created. Typically this requires passing a color, + or a color factory, from the client, down through the calls that + lead to the figure element factory. All programmers are familiar + with the inconvenience of adding a first argument to a number of + methods just to pass this kind of context information. + </para> + + <para> + Using AspectJ, this kind of context passing can be implemented in a + modular way. The following code adds after advice that runs only + when the factory methods of <classname>Figure</classname> are + called in the control flow of a method on a + <classname>ColorControllingClient</classname>. + </para> <programlisting><![CDATA[ aspect ColorControl { + pointcut CCClientCflow(ColorControllingClient client): + cflow(call(* * (..)) && target(client)); - pointcut CCClientCflow(ColorControllingClient client): - cflow(call(* * (..)) && target(client)); + pointcut make(): call(FigureElement Figure.make*(..)); - pointcut make(): call(FigureElement Figure.make*(..)); - - after (ColorControllingClient c) returning (FigureElement fe): - make() && CCClientCflow(c) { + after (ColorControllingClient c) returning (FigureElement fe): + make() && CCClientCflow(c) { + fe.setColor(c.colorFor(fe)); + } +} +]]></programlisting> - fe.setColor(c.colorFor(fe)); - } -}]]></programlisting> + <para> + This aspect affects only a small number of methods, but note that + the non-AOP implementation of this functionality might require + editing many more methods, specifically, all the methods in the + control flow from the client to the factory. This is a benefit + common to many property-based aspects while the aspect is short and + affects only a modest number of benefits, the complexity the aspect + saves is potentially much larger. + </para> - <para>This aspect affects only a small number of methods, but note that - the non-AOP implementation of this functionality might require editing - many more methods, specifically, all the methods in the control flow - from the client to the factory. This is a benefit common to many - property-based aspects while the aspect is short and affects only a - modest number of benefits, the complexity the aspect saves is - potentially much larger.</para> + </sect2> - </sect2> +<!-- ============================== --> - <sect2 id="consistentbehavior" xreflabel="Providing Consistent Behavior"> + <sect2 id="starting-production-consistentBehavior" xreflabel="Providing Consistent Behavior"> <title>Providing Consistent Behavior</title> - <para>This example shows how a property-based aspect can be used to + <para> + This example shows how a property-based aspect can be used to provide consistent handling of functionality across a large set of operations. This aspect ensures that all public methods of the - <literal>com.xerox</literal> package log any errors (a kind of - throwable, different from Exception) they throw to their caller. The - <function>publicMethodCall</function> pointcut captures the public - method calls of the package, and the after advice runs whenever one of - those calls returns throwing an exception. The advice logs the - exception and then the throw resumes.</para> + <literal>com.bigboxco</literal> package log any Errors they throw + to their caller (in Java, an Error is like an Exception, but it + indicates that something really bad and usually unrecoverable has + happened). The <function>publicMethodCall</function> pointcut + captures the public method calls of the package, and the after + advice runs whenever one of those calls throws an Error. The advice + logs that Error and then the throw resumes. + </para> <programlisting><![CDATA[ aspect PublicErrorLogging { - Log log = new Log(); + Log log = new Log(); - pointcut publicMethodCall(): call(public * com.xerox.*.*(..)); + pointcut publicMethodCall(): + call(public * com.bigboxco.*.*(..)); - after() throwing (Error e): publicMethodCall() { log.write(e); } -}]]></programlisting> - - <para>In some cases this aspect can log an exception twice. This happens - if code inside the <literal>com.xerox</literal> package itself calls a - public method of the package. In that case this code will log the error - at both the outermost call into the <literal>com.xerox</literal> - package and the re-entrant call. The <function>cflow</function> - primitive pointcut can be used in a nice way to exclude these - re-entrant calls:</para> + after() throwing (Error e): publicMethodCall() { + log.write(e); + } +} +]]></programlisting> - <programlisting><![CDATA[ -after() throwing (Error e): publicMethodCall() && - !cflow(publicMethodCall()) { - log.write(e); -}]]></programlisting> + <para> + In some cases this aspect can log an exception twice. This happens + if code inside the <literal>com.bigboxco</literal> package itself + calls a public method of the package. In that case this code will + log the error at both the outermost call into the + <literal>com.bigboxco</literal> package and the re-entrant + call. The <function>cflow</function> primitive pointcut can be used + in a nice way to exclude these re-entrant calls:</para> +<programlisting><![CDATA[ +after() throwing (Error e): + publicMethodCall() && !cflow(publicMethodCall()) { + log.write(e); +} +]]></programlisting> - <para>The following aspect is taken from work on the AspectJ compiler. + <para> + The following aspect is taken from work on the AspectJ compiler. The aspect advises about 35 methods in the - <classname>JavaParser</classname> class. The individual methods handle - each of the different kinds of elements that must be parsed. They have - names like <function>parseMethodDec</function>, + <classname>JavaParser</classname> class. The individual methods + handle each of the different kinds of elements that must be + parsed. They have names like <function>parseMethodDec</function>, <function>parseThrows</function>, and - <function>parseExpr</function>.</para> + <function>parseExpr</function>. + </para> - <programlisting><![CDATA[ +<programlisting><![CDATA[ aspect ContextFilling { - pointcut parse(JavaParser jp): - call(* JavaParser.parse*(..)) - && target(jp) - && !call(Stmt parseVarDec(boolean)); // var decs + pointcut parse(JavaParser jp): + call(* JavaParser.parse*(..)) + && target(jp) + && !call(Stmt parseVarDec(boolean)); // var decs // are tricky - around(JavaParser jp) returns ASTObject: parse(jp) { - Token beginToken = jp.peekToken(); - ASTObject ret = proceed(jp); - if (ret != null) jp.addContext(ret, beginToken); - return ret; - } -}]]></programlisting> + around(JavaParser jp) returns ASTObject: parse(jp) { + Token beginToken = jp.peekToken(); + ASTObject ret = proceed(jp); + if (ret != null) jp.addContext(ret, beginToken); + return ret; + } +} +]]></programlisting> - <para>This example exhibits a property found in many aspects with large + <para> + This example exhibits a property found in many aspects with large property-based pointcuts. In addition to a general property based - pattern <literal>call(* JavaParser.parse*(..))</literal> it includes an - exception to the pattern <literal>!call(Stmt + pattern <literal>call(* JavaParser.parse*(..))</literal> it + includes an exception to the pattern <literal>!call(Stmt parseVarDec(boolean))</literal>. The exclusion of <function>parseVarDec</function> happens because the parsing of variable declarations in Java is too complex to fit with the clean - pattern of the other <function>parse*</function> methods. Even with the - explicit exclusion this aspect is a clear expression of a clean - crosscutting modularity. Namely that all <function>parse*</function> - methods that return <classname>ASTObjects</classname>, except for + pattern of the other <function>parse*</function> methods. Even with + the explicit exclusion this aspect is a clear expression of a clean + crosscutting modularity. Namely that all + <function>parse*</function> methods that return + <classname>ASTObjects</classname>, except for <function>parseVarDec</function> share a common behavior for - establishing the parse context of their result. </para> - - <para>The process of writing an aspect with a large property-based - pointcut, and of developing the appropriate exceptions can clarify the - structure of the system. This is especially true, as in this case, when - refactoring existing code to use aspects. When we first looked at the - code for this aspect, we were able to use the IDE support provided in - AJDE for JBuilder to see what methods the aspect was advising compared - to our manual coding. We quickly discovered that there were a dozen - places where the aspect advice was in effect but we had not manually - inserted the required functionality. Two of these were bugs in our - prior non-AOP implementation of the parser. The other ten were needless - performance optimizations. So, here, refactoring the code to express - the crosscutting structure of the aspect explicitly made the code more - concise and eliminated latent bugs.</para> + establishing the parse context of their result. + </para> + <para> + The process of writing an aspect with a large property-based + pointcut, and of developing the appropriate exceptions can clarify + the structure of the system. This is especially true, as in this + case, when refactoring existing code to use aspects. When we first + looked at the code for this aspect, we were able to use the IDE + support provided in AJDE for JBuilder to see what methods the + aspect was advising compared to our manual coding. We quickly + discovered that there were a dozen places where the aspect advice + was in effect but we had not manually inserted the required + functionality. Two of these were bugs in our prior non-AOP + implementation of the parser. The other ten were needless + performance optimizations. So, here, refactoring the code to + express the crosscutting structure of the aspect explicitly made + the code more concise and eliminated latent bugs. + </para> </sect2> - </sect1> - <sect1> - <title>Static Crosscutting: Introduction</title> - <indexterm><primary>introduction</primary></indexterm> - - <para>Up until now we have only seen constructs that allow us to - implement dynamic crosscutting, crosscutting that changes the way a - program executes. AspectJ also allows us to implement static - crosscutting, crosscutting that affects the static structure of our - progams. This is done using forms called introduction.</para> - - <para>An <emphasis>introduction</emphasis> is a member of an aspect, but - it defines or modifies a member of another type (class). With - introduction we can</para> - <itemizedlist> - <listitem> - <para>add methods to an existing class</para> - </listitem> - <listitem> - <para>add fields to an existing class</para> - </listitem> - <listitem> - <para>extend an existing class with another</para> - </listitem> - <listitem> - <para>implement an interface in an existing class</para> - </listitem> - <listitem> - <para>convert checked exceptions into unchecked exceptions</para> - </listitem> - </itemizedlist> - - <para>Suppose we want to change the class - <classname>Point</classname> to support cloning. By using introduction, - we can add that capability. The class itself doesn't change, but its - users (here the method <function>main</function>) may. In the example - below, the aspect <classname>CloneablePoint</classname> does three - things: </para> - <orderedlist> - <listitem> - <para>declares that the class - <classname>Point</classname> implements the interface - <classname>Cloneable</classname>,</para> - </listitem> - <listitem> - <para>declares that the methods in <classname>Point</classname> whose - signature matches <literal>Object clone()</literal> should have - their checked exceptions converted into unchecked exceptions, - and</para> - </listitem> - <listitem> - <para>adds a method that overrides the method - <function>clone</function> in <classname>Point</classname>, which - was inherited from <classname>Object</classname>.</para> - </listitem> - </orderedlist> - - <programlisting> -class Point { - private int x, y; - - Point(int x, int y) { this.x = x; this.y = y; } - - int getX() { return this.x; } - int getY() { return this.y; } - - void setX(int x) { this.x = x; } - void setY(int y) { this.y = y; } - - public static void main(String[] args) { - - Point p = new Point(3,4); - Point q = (Point) p.clone(); - } -} +<!-- ============================== --> -aspect CloneablePoint { - declare parents: Point implements Cloneable; - - declare soft: CloneNotSupportedException: execution(Object clone()); - - Object Point.clone() { return super.clone(); } -}</programlisting> + <sect1 id="starting-conclusion"> + <title>Conclusion</title> - <para>Introduction is a powerful mechanism for capturing crosscutting - concerns because it not only changes the behavior of components in an - application, but also changes their relationship.</para> + <para> + AspectJ is a simple and practical aspect-oriented extension to + Java. With just a few new constructs, AspectJ provides support for + modular implementation of a range of crosscutting concerns. + </para> - </sect1> + <para> + Adoption of AspectJ into an existing Java development project can be + a straightforward and incremental task. One path is to begin by using + only development aspects, going on to using production aspects and + then reusable aspects after building up experience with + AspectJ. Adoption can follow other paths as well. For example, some + developers will benefit from using production aspects right + away. Others may be able to write clean reusable aspects almost right + away. + </para> - <sect1> - <title>Conclusion</title> + <para> + AspectJ enables both name-based and property based crosscutting. + Aspects that use name-based crosscutting tend to affect a small + number of other classes. But despite their small scale, they can + often eliminate significant complexity compared to an ordinary Java + implementation. Aspects that use property-based crosscutting can + have small or large scale. + </para> - <para>AspectJ is a simple and practical aspect-oriented extension to - Java. With just a few new constructs, AspectJ provides support for modular - implementation of a range of crosscutting concerns.</para> - - <para> Adoption of AspectJ into an existing Java development project can be - a straightforward and incremental task. One path is to begin by - using only development aspects, going on to using production aspects and - then reusable aspects after building up experience with AspectJ. Adoption - can follow other paths as well. For example, some developers will - benefit from using production aspects right away. Others may be able to - write clean reusable aspects almost right away.</para> - - <para>AspectJ enables both name-based and property based crosscutting. - Aspects that use name-based crosscutting tend to affect a small number of - other classes. But despite their small scale, they can often eliminate - significant complexity compared to an ordinary Java implementation. - Aspects that use property-based crosscutting can have small or large - scale.</para> - - <para>Using AspectJ results in clean well-modularized implementations of - crosscutting concerns. When written as an AspectJ aspect the structure - of a crosscutting concern is explicit and easy to understand. Aspects - are also highly modular, making it possible to develop plug-and-play - implementations of crosscutting functionality.</para> - - <para>AspectJ provides more functionality than was covered by this short - introduction. The next chapter, <xref linkend="aspectjlanguage"/>, covers - in detail all the features of the AspectJ language. The following - chapter, <xref linkend="examples"/>, then presents some carefully chosen - examples that show you how AspectJ might be used. We recommend that you - read the next two chapters carefully before deciding to adopt AspectJ - into a project. + <para> + Using AspectJ results in clean well-modularized implementations of + crosscutting concerns. When written as an AspectJ aspect the + structure of a crosscutting concern is explicit and easy to + understand. Aspects are also highly modular, making it possible to + develop plug-and-play implementations of crosscutting + functionality. </para> + <para> + AspectJ provides more functionality than was covered by this short + introduction. The next chapter, <xref linkend="language"/>, + covers in detail more of the features of the AspectJ language. The + following chapter, <xref linkend="examples"/>, then presents some + carefully chosen examples that show you how AspectJ might be used. We + recommend that you read the next two chapters carefully before + deciding to adopt AspectJ into a project. + </para> </sect1> - </chapter> - -<!-- -Local variables: -compile-command: "build.sh" -fill-column: 79 -sgml-local-ecat-files: progguide.ced -sgml-parent-document:("progguide.xml" "book" "chapter") -End: ---> diff --git a/docs/progGuideDB/idioms.xml b/docs/progGuideDB/idioms.xml index 5898dbd9e..c6297c90b 100644 --- a/docs/progGuideDB/idioms.xml +++ b/docs/progGuideDB/idioms.xml @@ -1,17 +1,20 @@ <chapter id="idioms" xreflabel="Idioms"> <title>Idioms</title> - <sect1><!-- About this Chapter --> - <title>About this Chapter</title> + <sect1 id="idioms-intro"> + <title>Introduction</title> - <para>This chapter consists of very short snippets of AspectJ code, - typically pointcuts, that are particularly evocative or useful. - This section is a work in progress. + <para> + This chapter consists of very short snippets of AspectJ code, + typically pointcuts, that are particularly evocative or useful. + This section is a work in progress. </para> - <para> Here's an example of how to enfore a rule that code in the java.sql - package can only be used from one particular package in your system. This - doesn't require any access to code in the java.sql package. + <para> + Here's an example of how to enfore a rule that code in the + java.sql package can only be used from one particular package in + your system. This doesn't require any access to code in the + java.sql package. </para> <programlisting><![CDATA[ @@ -19,7 +22,7 @@ pointcut restrictedCall(): call(* java.sql.*.*(..)) || call(java.sql.*.new(..)); -/* Any code in my system not in the sqlAccess package */ +/* Any code in my system not in the sqlAccess package */ pointcut illegalSource(): within(com.foo..*) && !within(com.foo.sqlAccess.*); @@ -31,9 +34,9 @@ declare error: restrictedCall() && illegalSource(): not exactly equal to AbstractFacade:</para> <programlisting><![CDATA[ -pointcut nonAbstract(AbstractFacade af): - call(* *(..)) - && target(af) +pointcut nonAbstract(AbstractFacade af): + call(* *(..)) + && target(af) && !if(af.getClass() == AbstractFacade.class); ]]></programlisting> @@ -42,7 +45,7 @@ pointcut nonAbstract(AbstractFacade af): <programlisting><![CDATA[ pointcut nonAbstract(AbstractFacade af): - call(* *(..)) + call(* *(..)) && target(af); ]]></programlisting> @@ -51,8 +54,8 @@ pointcut nonAbstract(AbstractFacade af): </para> <programlisting><![CDATA[ -pointcut callToUndefinedMethod(): - call(* AbstractFacade+.*(..)) +pointcut callToUndefinedMethod(): + call(* AbstractFacade+.*(..)) && !call(* AbstractFacade.*(..)); ]]></programlisting> @@ -62,43 +65,10 @@ pointcut callToUndefinedMethod(): <programlisting><![CDATA[ pointcut executionOfUndefinedMethod(): - execution(* *(..)) - && within(AbstractFacade+) + execution(* *(..)) + && within(AbstractFacade+) && !within(AbstractFacade) ]]></programlisting> - <para>To use a per-class variable declared on many classes, - you can defer initialization until you are in a non-static instance context - so you can refer to the particular class member. If you want to use - it from advice (without knowing the particular class at compile-time), - you can declare a method on the type. - </para> - -<programlisting><![CDATA[ -aspect Logging { - - //... - - /** per-Loggable-class reference to per-class Logger */ - static private Logger Loggable+.staticLogger; - - /** instance getter for static logger (lazy construction) */ - public Logger Loggable+.getLogger() { // XXX make private to aspect? - if (null == staticLogger) { - staticLogger = Logger.getLoggerFor(getClass()); - } - return staticLogger; - } - - /** when logging and logger enabled, log the target and join point */ - before(Loggable loggable) : target(loggable) && logging() { - Logger logger = loggable.getLogger(); - if (logger.enabled()) { - logger.log(loggable + " at " + thisJoinPoint); - } - } -} -]]></programlisting> - </sect1> </chapter> diff --git a/docs/progGuideDB/language.xml b/docs/progGuideDB/language.xml index 6a7a5dda3..709b5c764 100644 --- a/docs/progGuideDB/language.xml +++ b/docs/progGuideDB/language.xml @@ -1,29 +1,34 @@ -<chapter id="aspectjlanguage" xreflabel="The AspectJ Language"> +<chapter id="language" xreflabel="The AspectJ Language"> <title>The AspectJ Language</title> - <sect1> + <sect1 id="language-intro"> <title>Introduction</title> - <para>The previous chapter, <xref linkend="gettingstarted"/>, was a brief + <para> + The previous chapter, <xref linkend="starting" />, was a brief overview of the AspectJ language. You should read this chapter to - understand AspectJ's syntax and semantics. It covers the same material as - the previous chapter, but more completely and in much more detail. + understand AspectJ's syntax and semantics. It covers the same + material as the previous chapter, but more completely and in much + more detail. </para> - <para>We will start out by looking at an example aspect that we'll build + <para> + We will start out by looking at an example aspect that we'll build out of a pointcut, an introduction, and two pieces of advice. This - example aspect will gives us something concrete to talk about.</para> - + example aspect will gives us something concrete to talk about. + </para> </sect1> - <sect1 id="AnatomyOfAnAspect"> +<!-- ============================== --> + + <sect1 id="language-anatomy"> <title>The Anatomy of an Aspect</title> <para> This lesson explains the parts of AspectJ's aspects. By reading this - lesson you will have an overview of what's in an aspect and you will be - exposed to the new terminology introduced by AspectJ. + lesson you will have an overview of what's in an aspect and you will + be exposed to the new terminology introduced by AspectJ. </para> <sect2> @@ -60,18 +65,19 @@ ]]></programlisting> <para> - The <literal>FaultHandler</literal> consists of one variable introduced - onto <literal>Server</literal> (line 03), two methods (lines 05-07 - and 09-11), one pointcut (line 13), and two pieces of advice (lines - 15-17 and 19-22). + The <literal>FaultHandler</literal> consists of one inter-type + field on <literal>Server</literal> (line 03), two methods (lines + 05-07 and 09-11), one pointcut definition (line 13), and two pieces + of advice (lines 15-17 and 19-22). </para> <para> - This covers the basics of what aspects can contain. In general, aspects - consist of an association with other program entities, ordinary - variables and methods, pointcuts, introductions, and advice, where - advice may be before, after or around advice. The remainder of this - lesson focuses on those crosscut-related constructs. + This covers the basics of what aspects can contain. In general, + aspects consist of an association of other program entities, + ordinary variables and methods, pointcut definitions, inter-type declarations, + and advice, where advice may be before, after or around advice. The + remainder of this lesson focuses on those crosscut-related + constructs. </para> </sect2> @@ -79,11 +85,12 @@ <title>Pointcuts</title> <para> - AspectJ's pointcuts define collections of events, i.e. interesting - points in the execution of a program. These events, or points in the - execution, can be method or constructor invocations and executions, - handling of exceptions, field assignments and accesses, etc. Take, for - example, the pointcut declaration in line 13: + AspectJ's pointcut definitions give names to pointcuts. Pointcuts + themselves pick out join points, i.e. interesting points in the + execution of a program. These join points can be method or + constructor invocations and executions, the handling of exceptions, + field assignments and accesses, etc. Take, for example, the + pointcut definition in line 13: </para> <programlisting><![CDATA[ @@ -91,59 +98,65 @@ pointcut services(Server s): target(s) && call(public * *(..)) ]]></programlisting> <para> - This pointcut, named <literal>services</literal>, picks out those points - in the execution of the program when instances of the - <literal>Server</literal> class have their public methods called. + This pointcut, named <literal>services</literal>, picks out those + points in the execution of the program when + <literal>Server</literal> objects have their public methods called. + It also allows anyone using the <literal>services</literal> + pointcut to access the <literal>Server</literal> object whose + method is being called. </para> <para> - The idea behind this pointcut in the <literal>FaultHandler</literal> - aspect is that fault-handling-related behavior must be triggered on the - calls to public methods. For example, the server may be unable to - proceed with the request because of some fault. The calls of those - methods are, therefore, interesting events for this aspect, in the - sense that certain fault-related things will happen when these events + The idea behind this pointcut in the + <literal>FaultHandler</literal> aspect is that + fault-handling-related behavior must be triggered on the calls to + public methods. For example, the server may be unable to proceed + with the request because of some fault. The calls of those methods + are, therefore, interesting events for this aspect, in the sense + that certain fault-related things will happen when these events occur. </para> <para> - Part of the context in which the events occur is exposed by the formal - parameters of the pointcut. In this case, that consists of objects of - type server. That formal parameter is then being used on the right - hand side of the declaration in order to identify which events the - pointcut refers to. In this case, a pointcut picking out join points - where a Server is the target of some operation (target(s)) is being - composed (<literal><![CDATA[&&]]></literal>, meaning and) with a - pointcut picking out call join points (call(...)). The calls are - identified by signatures that can include wild cards. In this case, - there are wild cards in the return type position (first *), in the name - position (second *) and in the argument list position (..); the only - concrete information is given by the qualifier public. + Part of the context in which the events occur is exposed by the + formal parameters of the pointcut. In this case, that consists of + objects of type <literal>Server</literal>. That formal parameter + is then being used on the right hand side of the declaration in + order to identify which events the pointcut refers to. In this + case, a pointcut picking out join points where a Server is the + target of some operation (target(s)) is being composed + (<literal><![CDATA[&&]]></literal>, meaning and) with a pointcut + picking out call join points (call(...)). The calls are identified + by signatures that can include wild cards. In this case, there are + wild cards in the return type position (first *), in the name + position (second *) and in the argument list position (..); the + only concrete information is given by the qualifier + <literal>public</literal>. </para> - <sect3> - <title>What else?</title> - - <para> - Pointcuts define arbitrarily large sets of points in the execution - of a program. But they use only a finite number of - <emphasis>kinds</emphasis> of points. Those kinds of points - correspond to some of the most important concepts in Java. Here is - an incomplete list: method invocation, method execution, exception - handling, instantiation, constructor execution. Each of these has a - specific syntax that you will learn about in other parts of this - guide. - </para> - </sect3> + <para> + Pointcuts pick out arbitrarily large numbers of join points of a + program. But they pick out only a small number of + <emphasis>kinds</emphasis> of join points. Those kinds of join + points correspond to some of the most important concepts in + Java. Here is an incomplete list: method call, method execution, + exception handling, instantiation, constructor execution, and + field access. Each kind of join point can be picked out by its + own specialized pointcut that you will learn about in other parts + of this guide. + </para> </sect2> +<!-- ============================== --> + <sect2> <title>Advice</title> <para> - Advice defines pieces of aspect implementation that execute at join - points picked out by a pointcut. For example, the advice in lines 15-17 - specifies that the following piece of code + A piece of advice brings together a pointcut and a body of code to + define aspect implementation that runs at join points picked out by + the pointcut. For example, the advice in lines 15-17 specifies that + the following piece of code </para> <programlisting><![CDATA[ @@ -153,10 +166,10 @@ pointcut services(Server s): target(s) && call(public * *(..)) ]]></programlisting> <para> - is executed when instances of the Server class have their public - methods called, as specified by the pointcut services. More - specifically, it runs when those calls are made, just before the - corresponding methods are executed. + is executed when instances of the <literal>Server</literal> class + have their public methods called, as specified by the pointcut + <literal>services</literal>. More specifically, it runs when those + calls are made, just before the corresponding methods are executed. </para> <para> @@ -172,24 +185,23 @@ pointcut services(Server s): target(s) && call(public * *(..)) ]]></programlisting> <para> - But this second method executes whenever those operations throw + But this second method executes after those operations throw exception of type <literal>FaultException</literal>. </para> - <sect3> - <title>What else?</title> - <para> - There are two other variations of after advice: upon successful - return and upon return, either successful or with an exception. - There is also a third kind of advice called around. You will see - those in other parts of this guide. - </para> - </sect3> + <para> + There are two other variations of after advice: upon successful + return and upon return, either successful or with an exception. + There is also a third kind of advice called around. You will see + those in other parts of this guide. + </para> </sect2> </sect1> - <sect1> +<!-- ============================== --> + + <sect1 id="language-joinPoints"> <title>Join Points and Pointcuts</title> <para> @@ -211,9 +223,9 @@ class Point { ]]></programlisting> <para> - In order to get an intuitive understanding of AspectJ's pointcuts, let's - go back to some of the basic principles of Java. Consider the following a - method declaration in class Point: + In order to get an intuitive understanding of AspectJ's join points + and pointcuts, let's go back to some of the basic principles of + Java. Consider the following a method declaration in class Point: </para> <programlisting><![CDATA[ @@ -221,22 +233,29 @@ void setX(int x) { this.x = x; } ]]></programlisting> <para> - What this piece of program states is that when an object of type Point - has a method called setX with an integer as the argument called on it, - then the method body { this.x = x; } is executed. Similarly, the - constructor given in that class states that when an object of type Point - is instantiated through a constructor with two integers as arguments, - then the constructor body { this.x = x; this.y = y; } is executed. + This piece of program says that that when method named + <literal>setX</literal> with an <literal>int</literal> argument + called on an object of type <literal>Point</literal>, then the method + body <literal>{ this.x = x; }</literal> is executed. Similarly, the + constructor of the class states that when an object of type + <literal>Point</literal> is instantiated through a constructor with + two <literal>int</literal> arguments, then the constructor body + <literal>{ this.x = x; this.y = y; }</literal> is executed. </para> <para> - One pattern that emerges from these descriptions is when something - happens, then something gets executed. In object-oriented programs, there - are several kinds of "things that happen" that are determined by the - language. We call these the join points of Java. Join points comprised - method calls, method executions, instantiations, constructor executions, - field references and handler executions. (See the quick reference for - complete listing.) + One pattern that emerges from these descriptions is + + <blockquote> + When something happens, then something gets executed. + </blockquote> + + In object-oriented programs, there are several kinds of "things that + happen" that are determined by the language. We call these the join + points of Java. Join points consist of things like method calls, + method executions, object instantiations, constructor executions, + field references and handler executions. (See the <xref + linkend="quick" /> for a complete listing.) </para> <para> @@ -250,9 +269,9 @@ pointcut setter(): target(Point) && ]]></programlisting> <para> - describes the calls to <literal>setX(int)</literal> or - <literal>setY(int)</literal> methods of any instance of Point. Here's - another example: + picks out each call to <literal>setX(int)</literal> or + <literal>setY(int)</literal> when called on an instance of + <literal>Point</literal>. Here's another example: </para> <programlisting><![CDATA[ @@ -260,31 +279,26 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); ]]></programlisting> <para> - This pointcut picks out the join points at which exceptions of type - IOException are handled inside the code defined by class MyClass. - </para> - - <para> - Pointcuts consist of a left-hand side and a right-hand side, separated by - a colon. The left-hand side defines the pointcut name and the pointcut - parameters (i.e. the data available when the events happen). The - right-hand side defines the events in the pointcut. + This pointcut picks out each the join point when exceptions of type + <literal>IOException</literal> are handled inside the code defined by + class <literal>MyClass</literal>. </para> <para> - Pointcuts can then be used to define aspect code in advice, as we will - see later. But first let's see what types of events can be captured and - how they are described in AspectJ. + Pointcut definitions consist of a left-hand side and a right-hand side, + separated by a colon. The left-hand side consists of the pointcut name + and the pointcut parameters (i.e. the data available when the events + happen). The right-hand side consists of the pointcut itself. </para> <sect2> - <title>Designators</title> + <title>Some Example Pointcuts</title> <para> - Here are examples of designators of + Here are examples of pointcuts picking out </para> - <variablelist> + <variablelist> <varlistentry> <term>when a particular method body executes</term> <listitem> @@ -313,8 +327,11 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </varlistentry> <varlistentry> - <term>when the object currently executing - (i.e. <literal>this</literal>) is of type <literal>SomeType</literal></term> + <term> + when the object currently executing + (i.e. <literal>this</literal>) is of type + <literal>SomeType</literal> + </term> <listitem> <para> <literal>this(SomeType)</literal> @@ -323,8 +340,9 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </varlistentry> <varlistentry> - <term>when the target object is of type - <literal>SomeType</literal></term> + <term> + when the target object is of type <literal>SomeType</literal> + </term> <listitem> <para> <literal>target(SomeType)</literal> @@ -333,8 +351,10 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </varlistentry> <varlistentry> - <term>when the executing code belongs to - class <literal>MyClass</literal></term> + <term> + when the executing code belongs to + class <literal>MyClass</literal> + </term> <listitem> <para> <literal>within(MyClass)</literal> @@ -343,9 +363,11 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </varlistentry> <varlistentry> - <term>when the join point is in the control flow of a call to a - <literal>Test</literal>'s no-argument <literal>main</literal> method - </term> + <term> + when the join point is in the control flow of a call to a + <literal>Test</literal>'s no-argument <literal>main</literal> + method + </term> <listitem> <para> <literal>cflow(void Test.main())</literal> @@ -355,7 +377,7 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </variablelist> <para> - Designators compose through the operations <literal>or</literal> + Pointcuts compose through the operations <literal>or</literal> ("<literal>||</literal>"), <literal>and</literal> ("<literal><![CDATA[&&]]></literal>") and <literal>not</literal> ("<literal>!</literal>"). @@ -365,6 +387,7 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); <listitem> <para> It is possible to use wildcards. So + <orderedlist> <listitem> <para> @@ -378,10 +401,13 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </para> </listitem> </orderedlist> - means (1) all the executions of methods with any return and - parameter types and (2) method calls of set methods with any - return and parameter types -- in case of overloading there may be - more than one; this designator picks out all of them. + + means (1) the execution of any method regardless of return or + parameter types, and (2) the call to any method named + <literal>set</literal> regardless of return or parameter types + -- in case of overloading there may be more than one such + <literal>set</literal> method; this pointcut picks out calls to + all of them. </para> </listitem> @@ -414,21 +440,23 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </listitem> </orderedlist> - means (1) all executions of methods with no parameters, returning - an <literal>int</literal> (2) the calls of - <literal>setY</literal> methods that take a - <literal>long</literal> as an argument, regardless of their return - type or defining type, (3) the calls of class + + means (1) the execution of any method with no parameters that + returns an <literal>int</literal>, (2) the call to any + <literal>setY</literal> method that takes a + <literal>long</literal> as an argument, regardless of return + type or declaring type, (3) the call to any of <literal>Point</literal>'s <literal>setY</literal> methods that - take an <literal>int</literal> as an argument, regardless of the - return type, and (4) the calls of all classes' constructors that - take two <literal>int</literal>s as arguments. + take an <literal>int</literal> as an argument, regardless of + return type, and (4) the call to any classes' constructor, so + long as it takes exactly two <literal>int</literal>s as + arguments. </para> </listitem> <listitem> <para> - You can compose designators. For example, + You can compose pointcuts. For example, <orderedlist> <listitem> <para> @@ -450,30 +478,30 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); <listitem> <para> - <literal>this(*) <![CDATA[&&]]> !this(Point) <![CDATA[&&]]> - call(int *(..))</literal> + <literal> + !this(Point) <![CDATA[&&]]> call(int *(..)) + </literal> </para> </listitem> </orderedlist> - means (1) all calls to methods received by instances of class - <literal>Point</literal>, with no parameters, returning an - <literal>int</literal>, (2) calls to any method where the call is - made from the code in <literal>Point</literal>'s or - <literal>Line</literal>'s type declaration, (3) executions of - constructors of all classes, that take an <literal>int</literal> as - an argument, and - (4) all method calls of any method returning an - <literal>int</literal>, from all objects except - <literal>Point</literal> objects to any other objects. - + means (1) any call to an <literal>int</literal> method with no + arguments on an instance of <literal>Point</literal>, + regardless of its name, (2) any call to any method where the + call is made from the code in <literal>Point</literal>'s or + <literal>Line</literal>'s type declaration, (3) the execution of + any constructor taking exactly one <literal>int</literal> + argument, regardless of where the call is made from, and + (4) any method call to an <literal>int</literal> method when + the executing object is any type except <literal>Point</literal>. </para> </listitem> <listitem> <para> - You can select methods and constructors based on their modifiers - and on negations of modifiers. For example, you can say: + You can select methods and constructors based on their + modifiers and on negations of modifiers. For example, you can + say: <orderedlist> <listitem> <para> @@ -494,23 +522,27 @@ pointcut ioHandler(): within(MyClass) && handler(IOException); </listitem> </orderedlist> - which means (1) all invocation of public methods, (2) all - executions of non-static methods, and (3) all signatures of - the public, non-static methods. + which means (1) any call to a public method, (2) any + execution of a non-static method, and (3) any execution of a + public, non-static method. </para> </listitem> <listitem> <para> - Designators can also deal with interfaces. For example, given the + Pointcuts can also deal with interfaces. For example, given the interface </para> - <programlisting><![CDATA[ -interface MyInterface { ... }]]></programlisting> +<programlisting><![CDATA[ +interface MyInterface { ... } +]]></programlisting> - <para> the designator <literal>call(* MyInterface.*(..))</literal> - picks out the call join points for methods defined by the interface - <literal>MyInterface</literal> (or its superinterfaces). + <para> + the pointcut <literal>call(* MyInterface.*(..))</literal> picks + out any call to a method in <literal>MyInterface</literal>'s + signature -- that is, any method defined by + <literal>MyInterface</literal> or inherited by one of its a + supertypes. </para> </listitem> @@ -528,55 +560,64 @@ interface MyInterface { ... }]]></programlisting> <para> AspectJ exposes these times as call and execution join points, - respectively, and allows them to be picked out specifically by call and - execution pointcuts. + respectively, and allows them to be picked out specifically by + <literal>call</literal> and <literal>execution</literal> pointcuts. </para> <para> - So what's the difference between these times? Well, there are a number - of differences: + So what's the difference between these join points? Well, there are a + number of differences: </para> <para> - Firstly, the lexical pointcut declarations <literal>within</literal> - and <literal>withincode</literal> match differently. At a call join - point, the enclosing text is that of the call site. This means that - This means that <literal>call(void m()) <![CDATA[&&]]> within(void m())</literal> - will only capture recursive calls, for example. At an execution join - point, however, the control is already executing the method. + Firstly, the lexical pointcut declarations + <literal>within</literal> and <literal>withincode</literal> match + differently. At a call join point, the enclosing code is that of + the call site. This means that <literal>call(void m()) + <![CDATA[&&]]> withincode(void m())</literal> will only capture + directly recursive calls, for example. At an execution join point, + however, the program is already executing the method, so the + enclosing code is the method itself: <literal>execution(void m()) + <![CDATA[&&]]> withincode(void m())</literal> is the same as + <literal>execution(void m())</literal>. </para> <para> Secondly, the call join point does not capture super calls to non-static methods. This is because such super calls are different in - Java, since they don't behave via dynamic dispatch like other calls to - non-static methods. + Java, since they don't behave via dynamic dispatch like other calls to + non-static methods. </para> <para> - The rule of thumb is that if you want to pick a join point that runs - when an actual piece of code runs, pick an execution, but if you want - to pick one that runs when a particular signature is called, pick a - call. + The rule of thumb is that if you want to pick a join point that + runs when an actual piece of code runs (as is often the case for + tracing), use <literal>execution</literal>, but if you want to pick + one that runs when a particular <emphasis>signature</emphasis> is + called (as is often the case for production aspects), use + <literal>call</literal>. </para> </sect2> - +<!-- ============================== --> <sect2> <title>Pointcut composition</title> - <para>Pointcuts are put together with the operators and (spelled - <literal>&&</literal>), or (spelled <literal>||</literal>), and - not (spelled <literal>!</literal>). This allows the creation of very - powerful pointcuts from the simple building blocks of primitive - pointcuts. This composition can be somewhat confusing when used with - primitive pointcuts like cflow and cflowbelow. Here's an example: + <para> + Pointcuts are put together with the operators and (spelled + <literal>&&</literal>), or (spelled <literal>||</literal>), + and not (spelled <literal>!</literal>). This allows the creation + of very powerful pointcuts from the simple building blocks of + primitive pointcuts. This composition can be somewhat confusing + when used with primitive pointcuts like <literal>cflow</literal> + and <literal>cflowbelow</literal>. Here's an example: </para> - <para> <literal>cflow(<replaceable>P</replaceable>)</literal> picks out - the join points in the control flow of the join points picked out by - <replaceable>P</replaceable>. So, pictorially: + <para> + <literal>cflow(<replaceable>P</replaceable>)</literal> picks out + each join point in the control flow of the join points picked out + by <replaceable>P</replaceable>. So, pictorially: </para> <programlisting> @@ -587,11 +628,12 @@ interface MyInterface { ... }]]></programlisting> </programlisting> - <para>What does <literal>cflow(<replaceable>P</replaceable>) && - cflow(<replaceable>Q</replaceable>)</literal> pick out? Well, it picks - out those join points that are in both the control flow of - <replaceable>P</replaceable> and in the control flow of - <replaceable>Q</replaceable>. So... + <para> + What does <literal>cflow(<replaceable>P</replaceable>) && + cflow(<replaceable>Q</replaceable>)</literal> pick out? Well, it + picks out each join point that is in both the control flow of + <replaceable>P</replaceable> and in the control flow of + <replaceable>Q</replaceable>. So... </para> <programlisting> @@ -607,15 +649,18 @@ interface MyInterface { ... }]]></programlisting> \ \ </programlisting> - <para>Note that <replaceable>P</replaceable> and <replaceable>Q</replaceable> might - not have any join points in common... but their control flows might have join - points in common. + <para> + Note that <replaceable>P</replaceable> and + <replaceable>Q</replaceable> might not have any join points in + common... but their control flows might have join points in common. </para> - <para>But what does <literal>cflow(<replaceable>P</replaceable> - && <replaceable>Q</replaceable>)</literal> mean? Well, it means - the control flow of those join points that are both picked out by - <replaceable>P</replaceable> picked out by <replaceable>Q</replaceable>. + <para> + But what does <literal>cflow(<replaceable>P</replaceable> + && <replaceable>Q</replaceable>)</literal> mean? Well, it + means the control flow of those join points that are both picked + out by <replaceable>P</replaceable> and picked out by + <replaceable>Q</replaceable>. </para> <programlisting> @@ -625,21 +670,24 @@ interface MyInterface { ... }]]></programlisting> \ </programlisting> - <para>and if there are <emphasis>no</emphasis> join points that are both picked by - <replaceable>P</replaceable> and picked out by <replaceable>Q</replaceable>, - then there's no chance that there are any join points in the control flow of - <literal>(<replaceable>P</replaceable> && - <replaceable>Q</replaceable>)</literal>. + <para> + and if there are <emphasis>no</emphasis> join points that are both + picked by <replaceable>P</replaceable> and picked out by + <replaceable>Q</replaceable>, then there's no chance that there are + any join points in the control flow of + <literal>(<replaceable>P</replaceable> && + <replaceable>Q</replaceable>)</literal>. </para> - <para>Here's some code that expresses this. + <para> + Here's some code that expresses this. </para> <programlisting><![CDATA[ public class Test { public static void main(String[] args) { foo(); - } + } static void foo() { goo(); } @@ -649,7 +697,6 @@ public class Test { } aspect A { - pointcut fooPC(): execution(void Test.foo()); pointcut gooPC(): execution(void Test.goo()); pointcut printPC(): call(void java.io.PrintStream.println(String)); @@ -661,17 +708,18 @@ aspect A { before(): cflow(fooPC() && gooPC()) && printPC() { System.out.println("should not occur"); } - } ]]></programlisting> </sect2> +<!-- ============================== --> + <sect2> <title>Pointcut Parameters</title> <para> - Consider, for example, the first pointcut you've seen here, + Consider again the first pointcut definition in this chapter: </para> <programlisting><![CDATA[ @@ -681,13 +729,14 @@ aspect A { ]]></programlisting> <para> - As we've seen before, the right-hand side of the pointcut picks out the - calls to <literal>setX(int)</literal> or <literal>setY(int)</literal> - methods where the target is any object of type - <literal>Point</literal>. On the left-hand side, the pointcut is given - the name "setters" and no parameters. An empty parameter list means - that when those events happen no context is immediately available. But - consider this other version of the same pointcut: + As we've seen, this pointcut picks out each call to + <literal>setX(int)</literal> or <literal>setY(int)</literal> + methods where the target is an instance of + <literal>Point</literal>. The pointcut is given the name + <literal>setters</literal> and no parameters on the left-hand + side. An empty parameter list means that none of the context from + the join points is published from this pointcut. But consider + another version of version of this pointcut definition: </para> <programlisting><![CDATA[ @@ -697,13 +746,15 @@ aspect A { ]]></programlisting> <para> - This version picks out exactly the same calls. But in this version, the - pointcut has one parameter of type <literal>Point</literal>. This means - that when the events described on the right-hand side happen, a - <literal>Point</literal> object, named by a parameter named "p", is - available. According to the right-hand side of the pointcut, that - <literal>Point</literal> object in the pointcut parameters is the - object that receives the calls. + This version picks out exactly the same join points. But in this + version, the pointcut has one parameter of type + <literal>Point</literal>. This means that any advice that uses this + pointcut has access to a <literal>Point</literal> from each join + point picked out by the pointcut. Inside the pointcut definition + this <literal>Point</literal> is named <literal>p</literal> is + available, and according to the right-hand side of the definition, + that <literal>Point p</literal> comes from the + <literal>target</literal> of each matched join point. </para> <para> @@ -718,16 +769,19 @@ aspect A { ]]></programlisting> <para> - This pointcut also has a parameter of type <literal>Point</literal>. - Similarly to the "setters" pointcut, this means that when the events - described on the right-hand side happen, a <literal>Point</literal> - object, named by a parameter named "p", is available. But in this case, - looking at the right-hand side, we find that the object named in the - parameters is not the target <literal>Point</literal> object that receives the - call; it's the argument (of type Point) passed to the "equals" method on some other - target Point object. If we wanted access to both objects, then the pointcut - definition that would define target <literal>Point p1</literal> - and argument <literal>Point p2</literal> would be + This pointcut also has a parameter of type + <literal>Point</literal>. Similar to the + <literal>setters</literal> pointcut, this means that anyone using + this pointcut has access to a <literal>Point</literal> from each + join point. But in this case, looking at the right-hand side we + find that the object named in the parameters is not the target + <literal>Point</literal> object that receives the call; it's the + argument (also of type <literal>Point</literal>) passed to the + <literal>equals</literal> method when some other + <literal>Point</literal> is the target. If we wanted access to both + <literal>Point</literal>s, then the pointcut definition that would + expose target <literal>Point p1</literal> and argument + <literal>Point p2</literal> would be </para> <programlisting><![CDATA[ @@ -737,7 +791,7 @@ aspect A { ]]></programlisting> <para> - Let's look at another variation of the "setters" pointcut: + Let's look at another variation of the <literal>setters</literal> pointcut: </para> <programlisting><![CDATA[ @@ -748,49 +802,47 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> <para> - In this case, a <literal>Point</literal> object and an integer value - are available when the calls happen. Looking at the events definition - on the right-hand side, we find that the <literal>Point</literal> - object is the object receiving the call, and the integer - value is the argument of the method . + In this case, a <literal>Point</literal> object and an + <literal>int</literal> value are exposed by the named + pointcut. Looking at the the right-hand side of the definition, we + find that the <literal>Point</literal> object is the target object, + and the <literal>int</literal> value is the called method's + argument. </para> <para> - The definition of pointcut parameters is relatively flexible. The most - important rule is that when each of those events defined in the - right-hand side happen, all the pointcut parameters must be bound to - some value. So, for example, the following pointcut definition will - result in a compilation error: - </para> + The use of pointcut parameters is relatively flexible. The most + important rule is that all the pointcut parameters must be bound at + every join point picked out by the pointcut. So, for example, the + following pointcut definition will result in a compilation error: <programlisting><![CDATA[ - pointcut xcut(Point p1, Point p2): + pointcut badPointcut(Point p1, Point p2): (target(p1) && call(void setX(int))) || (target(p2) && call(void setY(int))); ]]></programlisting> - <para> - The right-hand side establishes that this pointcut picks out the call - join points consisting of the <literal>setX(int)</literal> method - called on a point object, or the <literal>setY(int)</literal> method - called on a point object. This is fine. The problem is that the - parameters definition tries to get access to two point objects. But - when <literal>setX(int)</literal> is called on a point object, there is - no other point object to grab! So in that case, the parameter - <literal>p2</literal> is unbound, and hence, the compilation error. + because <literal>p1</literal> is only bound when calling + <literal>setX</literal>, and <literal>p2</literal> is only bound + when calling <literal>setY</literal>, but the pointcut picks out + all of these join points and tries to bind both + <literal>p1</literal> and <literal>p2</literal>. </para> - </sect2> +<!-- ============================== --> + <sect2> <title>Example: <literal>HandleLiveness</literal></title> <para> The example below consists of two object classes (plus an exception - class) and one aspect. Handle objects delegate their public, non-static - operations to their <literal>Partner</literal> objects. The aspect - <literal>HandleLiveness</literal> ensures that, before the delegations, - the partner exists and is alive, or else it throws an exception.</para> + class) and one aspect. Handle objects delegate their public, + non-static operations to their <literal>Partner</literal> + objects. The aspect <literal>HandleLiveness</literal> ensures that, + before the delegations, the partner exists and is alive, or else it + throws an exception. + </para> <programlisting><![CDATA[ class Handle { @@ -824,17 +876,19 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> </sect2> - </sect1> - <sect1> +<!-- ============================== --> + + <sect1 id="language-advice"> <title>Advice</title> <para> Advice defines pieces of aspect implementation that execute at - well-defined points in the execution of the program. Those points can be - given either by named pointcuts (like the ones you've seen above) or by - anonymous pointcuts. Here is an example of an advice on a named pointcut: + well-defined points in the execution of the program. Those points can + be given either by named pointcuts (like the ones you've seen above) + or by anonymous pointcuts. Here is an example of an advice on a named + pointcut: </para> <programlisting><![CDATA[ @@ -866,6 +920,11 @@ pointcut setter(Point p, int newval): target(p) && Here are examples of the different advice: </para> + <para> + This before advice runs just before the join points picked out by the + (anonymous) pointcut: + </para> + <programlisting><![CDATA[ before(Point p, int x): target(p) && args(x) && call(void setX(int)) { if (!p.assertX(x)) return; @@ -873,8 +932,9 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> <para> - This before advice runs just before the execution of the actions - associated with the events in the (anonymous) pointcut. + This after advice runs just after each join point picked out by the + (anonymous) pointcut, regardless of whether it returns normally or throws + an exception: </para> <programlisting><![CDATA[ @@ -884,9 +944,10 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> <para> - This after advice runs just after each join point picked out by the - (anonymous) pointcut, regardless of whether it returns normally or throws - an exception. + This after returning advice runs just after each join point picked + out by the (anonymous) pointcut, but only if it returns normally. + The return value can be accessed, and is named <literal>x</literal> + here. After the advice runs, the return value is returned: </para> <programlisting><![CDATA[ @@ -896,10 +957,11 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> <para> - This after returning advice runs just after each join point picked out by - the (anonymous) pointcut, but only if it returns normally. The return - value can be accessed, and is named <literal>x</literal> here. After the - advice runs, the return value is returned. + This after throwing advice runs just after each join point picked out by + the (anonymous) pointcut, but only when it throws an exception of type + <literal>Exception</literal>. Here the exception value can be accessed + with the name <literal>e</literal>. The advice re-raises the exception + after it's done: </para> <programlisting><![CDATA[ @@ -909,11 +971,10 @@ pointcut setter(Point p, int newval): target(p) && ]]></programlisting> <para> - This after throwing advice runs just after each join point picked out by - the (anonymous) pointcut, but only when it throws an exception of type - <literal>Exception</literal>. Here the exception value can be accessed - with the name <literal>e</literal>. The advice re-raises the exception - after it's done. + This around advice traps the execution of the join point; it runs + <emphasis>instead</emphasis> of the join point. The original action + associated with the join point can be invoked through the special + <literal>proceed</literal> call: </para> <programlisting><![CDATA[ @@ -924,146 +985,167 @@ void around(Point p, int x): target(p) p.releaseResources(); } ]]></programlisting> - - <para> - This around advice traps the execution of the join point; it runs - <emphasis>instead</emphasis> of the join point. The original action - associated with the join point can be invoked through the special - <literal>proceed</literal> call. - </para> - </sect1> - <sect1> - <title>Introduction</title> +<!-- ============================== --> + + <sect1 id="language-interType"> + <title>Inter-type declarations</title> <para> - Introduction declarations add whole new elements in the given types, and - so change the type hierarchy. Here are examples of introduction + Aspects can declare members (fields, methods, and constructors) that + are owned by other types. These are called inter-type members. + Aspects can also declare that other types implement new interfaces or + extend a new class. Here are examples of some such inter-type declarations: </para> + <para> + This declares that each <literal>Server</literal> has a + <literal>boolean</literal> field named <literal>disabled</literal>, + initialized to <literal>false</literal>: + <programlisting><![CDATA[ private boolean Server.disabled = false; ]]></programlisting> - <para> - This privately introduces a field named <literal>disabled</literal> in - <literal>Server</literal> and initializes it to - <literal>false</literal>. Because it is declared - <literal>private</literal>, only code defined in the aspect can access - the field. + It is declared <literal>private</literal>, which means that it is + private <emphasis>to the aspect</emphasis>: only code in the aspect + can see the field. And even if <literal>Server</literal> has + another private field named <literal>disabled</literal> (declared in + <literal>Server</literal> or in another aspect) there won't be a name + collision, since no reference to <literal>disabled</literal> will be + ambiguous. </para> + <para> + This declares that each <literal>Point</literal> has an + <literal>int</literal> method named <literal>getX</literal> with no + arguments that returns whatever <literal>this.x</literal> is: + <programlisting><![CDATA[ - public int Point.getX() { return x; } + public int Point.getX() { return this.x; } ]]></programlisting> - <para> - This publicly introduces a method named <literal>getX</literal> in - <literal>Point</literal>; the method returns an <literal>int</literal>, - it has no arguments, and its body is return <literal>x</literal>. - Because it is defined publically, any code can call it. + Inside the body, <literal>this</literal> is the + <literal>Point</literal> object currently executing. Because the + method is publically declared any code can call it, but if there is + some other <literal>Point.getX()</literal> declared there will be a + compile-time conflict. </para> + <para> + This publically declares a two-argument constructor for + <literal>Point</literal>: + <programlisting><![CDATA[ public Point.new(int x, int y) { this.x = x; this.y = y; } ]]></programlisting> - <para> - This publicly introduces a constructor in Point; the constructor has - two arguments of type int, and its body is this.x = x; this.y = y; </para> + <para> + This publicly declares that each <literal>Point</literal> has an + <literal>int</literal> field named <literal>x</literal>, initialized + to zero: + <programlisting><![CDATA[ public int Point.x = 0; ]]></programlisting> - <para> - This publicly introduces a field named x of type int in Point; the - field is initialized to 0. + Because this is publically declared, it is an error if + <literal>Point</literal> already has a field named + <literal>x</literal> (defined by <literal>Point</literal> or by + another aspect). </para> + <para> + This declares that the <literal>Point</literal> class implements the + <literal>Comparable</literal> interface: + <programlisting><![CDATA[ declare parents: Point implements Comparable; ]]></programlisting> - <para> - This declares that the <literal>Point</literal> class now implements the - <literal>Comparable</literal> interface. Of course, this will be an error - unless <literal>Point</literal> defines the methods of - <literal>Comparable</literal>. + Of course, this will be an error unless <literal>Point</literal> + defines the methods required by <literal>Comparable</literal>. </para> + <para> + This declares that the <literal>Point</literal> class extends the + <literal>GeometricObject</literal> class. + <programlisting><![CDATA[ declare parents: Point extends GeometricObject; ]]></programlisting> - - <para> - This declares that the <literal>Point</literal> class now extends the - <literal>GeometricObject</literal> class. </para> <para> - An aspect can introduce several elements in at the same time. For - example, the following declaration - </para> + An aspect can have several inter-type declarations. For example, the + following declarations <programlisting><![CDATA[ public String Point.name; public void Point.setName(String name) { this.name = name; } ]]></programlisting> - <para> - publicly introduces both a field and a method into class - <literal>Point</literal>. Note that the identifier "name" in the body of - the method is bound to the "name" field in <literal>Point</literal>, even - if the aspect defined another field called "name". + publicly declare that Point has both a String field + <literal>name</literal> and a <literal>void</literal> method + <literal>setName(String)</literal> (which refers to the + <literal>name</literal> field declared by the aspect). </para> <para> - One declaration can introduce several elements in several classes as - well. For example, - </para> + An inter-type member can only have one target type, but often you may + wish to declare the same member on more than one type. This can be + done by using an inter-type member in combination with a private + interface: <programlisting><![CDATA[ - public String (Point || Line || Square).getName() { return name; } + aspect A { + private interface HasName {} + declare parents: (Point || Line || Square) implements HasName; + + private String HasName.name; + public String HasName.getName() { return name; } + } ]]></programlisting> - <para> - publicly introduces three methods, one in <literal>Point</literal>, - another in Line and another in <literal>Square</literal>. The three - methods have the same name (getName), no parameters, return a String, and - have the same body (return name;). The purpose of introducing several - elements in one single declaration is that their bodies are the same. The - introduction is an error if any of <literal>Point</literal>, - <literal>Line</literal>, or <literal>Square</literal> do not have a - "name" field. + This declares a marker interface <literal>HasName</literal>, and also declares that any + type that is either <literal>Point</literal>, + <literal>Line</literal>, or <literal>Square</literal> implements that + interface. It also privately declares that all <literal>HasName</literal> + object have a <literal>String</literal> field called + <literal>name</literal>, and publically declares that all + <literal>HasName</literal> objects have a <literal>String</literal> + method <literal>getName()</literal> (which refers to the privately + declared <literal>name</literal> field). </para> <para> - An aspect can introduce fields and methods (even with bodies) onto - interfaces as well as classes. + As you can see from the above example, an aspect can declare that + interfaces have fields and methods, even non-constant fields and + methods with bodies. </para> +<!-- ============================== --> + <sect2> - <title>Introduction Scope</title> + <title>Inter-type Scope</title> <para> - AspectJ allows private and package-protected (default) introduction in - addition to public introduction. Private introduction means private in + AspectJ allows private and package-protected (default) inter-type declarations in + addition to public inter-type declarations. Private means private in relation to the aspect, not necessarily the target type. So, if an - aspect makes a private introduction of a field on a type - </para> + aspect makes a private inter-type declaration of a field <programlisting><![CDATA[ private int Foo.x; ]]></programlisting> - <para> - Then code in the aspect can refer to Foo's x field, but nobody else - can. Similarly, if an aspect makes a package-protected - introduction, + Then code in the aspect can refer to <literal>Foo</literal>'s + <literal>x</literal> field, but nobody else can. Similarly, if an + aspect makes a package-protected introduction, </para> <programlisting><![CDATA[ @@ -1071,22 +1153,27 @@ void around(Point p, int x): target(p) ]]></programlisting> <para> - then everything in the aspect's package (which may not be Foo's - package) can access x. + then everything in the aspect's package (which may or may not be + <literal>Foo</literal>'s package) can access <literal>x</literal>. </para> </sect2> +<!-- ============================== --> + <sect2> <title>Example: <literal>PointAssertions</literal></title> + <para> The example below consists of one class and one aspect. The aspect - introduces all implementation that is related with assertions of the - class. It privately introduces two methods in the class Point, namely - assertX and assertY. It also advises the two set methods of Point with - before declarations that assert the validity of the given values. The - introductions are made privately because other parts of the program - have no business accessing the assert methods. Only the code inside of - the aspect can call those methods. + privately declares the assertion methods of + <literal>Point</literal>, <literal>assertX</literal> and + <literal>assertY</literal>. It also guards calls to + <literal>setX</literal> and <literal>setY</literal> with calls to + these assertion methods. The assertion methods are declared + privately because other parts of the program (including the code in + <literal>Point</literal>) have no business accessing the assert + methods. Only the code inside of the aspect can call those + methods. </para> <programlisting><![CDATA[ @@ -1124,27 +1211,29 @@ void around(Point p, int x): target(p) } ]]></programlisting> - </sect2> + </sect2> </sect1> <!-- ================================================== --> - <sect1> - <title>Reflection</title> + <sect1 id="language-thisJoinPoint"> + <title>thisJoinPoint</title> <para> - AspectJ provides a special reference variable, thisJoinPoint, that - contains reflective information about the current join point for the - advice to use. The thisJoinPoint variable can only be used in the context - of advice, just like this can only be used in the context of non-static - methods and variable initializers. In advice, thisJoinPoint is an object - of type JoinPoint. + AspectJ provides a special reference variable, + <literal>thisJoinPoint</literal>, that contains reflective + information about the current join point for the advice to use. The + <literal>thisJoinPoint</literal> variable can only be used in the + context of advice, just like <literal>this</literal> can only be used + in the context of non-static methods and variable initializers. In + advice, <literal>thisJoinPoint</literal> is an object of type <ulink + url="../api/org/aspectj/lang/JoinPoint.html"><literal>org.aspectj.lang.JoinPoint</literal></ulink>. </para> <para> - One way to use it is simply to print it out. Like all Java objects, - thisJoinPoint has a toString() method that makes quick-and-dirty tracing - easy. + One way to use it is simply to print it out. Like all Java objects, + <literal>thisJoinPoint</literal> has a <literal>toString()</literal> + method that makes quick-and-dirty tracing easy: </para> <programlisting><![CDATA[ @@ -1156,33 +1245,29 @@ void around(Point p, int x): target(p) ]]></programlisting> <para> - The type of thisJoinPoint includes a rich reflective class hierarchy of - signatures, and can be used to access both static and dynamic information - about join points. If, however, only the static information about the - join point (such as the Signature) is desired, a lightweight join-point - object is available from the thisJoinPointStaticPart special variable. - This object is the same object you would get from - </para> - + The type of <literal>thisJoinPoint</literal> includes a rich + reflective class hierarchy of signatures, and can be used to access + both static and dynamic information about join points such as the + arguments of the join point: <programlisting><![CDATA[ - thisJoinPoint.getStaticPart() + thisJoinPoint.getArgs() ]]></programlisting> - <para> - The static part of a join point does not include dynamic information, - such as the arguments, which can be accessed with - </para> + In addition, it holds an object consisting of all the static + information about the join point such as corresponding line number + and static signature: <programlisting><![CDATA[ - thisJoinPoint.getArgs() + thisJoinPoint.getStaticPart() ]]></programlisting> - <para> - But it has the performance benefit that repeated execution of the code - containing <literal>thisJoinPointStaticPart</literal> (through, for - example, separate method calls) will not result in repeated construction - of the reflective object. + If you only need the static information about the join point, you may + access the static part of the join point directly with the special + variable <literal>thisJoinPointStaticPart</literal>. Using + <literal>thisJoinPointStaticPart</literal> will avoid the run-time + creation of the join point object that may be necessary when using + <literal>thisJoinPoint</literal> directly. </para> <para>It is always the case that @@ -1199,13 +1284,12 @@ void around(Point p, int x): target(p) <para> One more reflective variable is available: <literal>thisEnclosingJoinPointStaticPart</literal>. This, like - <literal>thisJoinPointStaticPart</literal>, only holds the static part of - a join point, but it is not the current but the enclosing join point. - So, for example, it is possible to print out the calling source location - (if available) with + <literal>thisJoinPointStaticPart</literal>, only holds the static + part of a join point, but it is not the current but the enclosing + join point. So, for example, it is possible to print out the calling + source location (if available) with </para> - <programlisting><![CDATA[ before() : execution (* *(..)) { System.err.println(thisEnclosingJoinPointStaticPart.getSourceLocation()) @@ -1213,12 +1297,4 @@ void around(Point p, int x): target(p) ]]></programlisting> </sect1> - </chapter> - -<!-- Local variables: --> -<!-- fill-column: 79 --> -<!-- compile-command: "ant -quiet prog-html" --> -<!-- sgml-local-ecat-files: progguide.ced --> -<!-- sgml-parent-document:("progguide.xml" "book" "chapter") --> -<!-- End: --> diff --git a/docs/progGuideDB/limitations.xml b/docs/progGuideDB/limitations.xml index 41e10db45..b5d574738 100644 --- a/docs/progGuideDB/limitations.xml +++ b/docs/progGuideDB/limitations.xml @@ -3,15 +3,18 @@ <title>Implementation Limitations</title> <para> - Certain elements of AspectJ's semantics are difficult to implement without - making modifications to the virtual machine. One way to deal with this - problem would be to specify only the behavior that is easiest to implement. - We have chosen a somewhat different approach, which is to specify an ideal - language semantics, as well as a clearly defined way in which - implementations are allowed to deviate from that semantics. This makes it - possible to develop conforming AspectJ implementations today, while still - making it clear what later, and presumably better, implementations should do - tomorrow. + The initial implementations of AspectJ have all been + compiler-based implementations. Certain elements of AspectJ's + semantics are difficult to implement without making modifications + to the virtual machine, which a compiler-based implementation + cannot do. One way to deal with this problem would be to specify + only the behavior that is easiest to implement. We have chosen a + somewhat different approach, which is to specify an ideal language + semantics, as well as a clearly defined way in which + implementations are allowed to deviate from that semantics. This + makes it possible to develop conforming AspectJ implementations + today, while still making it clear what later, and presumably + better, implementations should do tomorrow. </para> <para> @@ -19,105 +22,85 @@ </para> <programlisting><![CDATA[ -before(): get(int Point.x) { System.out.println("got x"); } + before(): get(int Point.x) { System.out.println("got x"); } ]]></programlisting> <para> - should advise all accesses of a field of type int and name x from instances - of type (or subtype of) Point. It should do this regardless of whether all - the source code performing the access was available at the time the aspect - containing this advice was compiled, whether changes were made later, etc. + should advise all accesses of a field of type int and name x from + instances of type (or subtype of) Point. It should do this + regardless of whether all the source code performing the access + was available at the time the aspect containing this advice was + compiled, whether changes were made later, etc. </para> <para> - But AspectJ implementations are permitted to deviate from this in a - well-defined way -- they are permitted to advise only accesses in - <emphasis>code the implementation controls</emphasis>. Each implementation - is free within certain bounds to provide its own definition of what it means - to control code. + But AspectJ implementations are permitted to deviate from this in + a well-defined way -- they are permitted to advise only accesses + in <emphasis>code the implementation controls</emphasis>. Each + implementation is free within certain bounds to provide its own + definition of what it means to control code. </para> <para> - In the current AspectJ compiler, ajc, control of the code means having - source code for any aspects and all the code they should affect available - during the compile. This means that if some class Client contains code with - the expression <literal>new Point().x</literal> (which results in a field - get join point at runtime), the current AspectJ compiler will fail to advise - that access unless Client.java is compiled at the same the aspect is - compiled. It also means that join points associated with code in precompiled - libraries (such as java.lang), and join points associated with code in - native methods (including their execution join points), can not be advised. + In the current AspectJ compiler, ajc, control of the code means + having bytecode for any aspects and all the code they should + affect available during the compile. This means that if some class + Client contains code with the expression <literal>new + Point().x</literal> (which results in a field get join point at + runtime), the current AspectJ compiler will fail to advise that + access unless Client.java or Client.class is compiled as well. It + also means that join points associated with code in native methods + (including their execution join points) cannot be advised. </para> <para> - Different join points have different requirements. Method call join points - can be advised only if ajc controls <emphasis>either</emphasis> the code for - the caller or the code for the receiver, and some call pointcut designators - may require caller context (what the static type of the receiver is, for - example) to pick out join points. Constructor call join points can be - advised only if ajc controls the code for the caller. Field reference or - assignment join points can be advised only if ajc controls the code for the - "caller", the code actually making the reference or assignment. - Initialization join points can be advised only if ajc controls the code of - the type being initialized, and execution join points can be advised only if - ajc controls the code for the method or constructor body in question. + Different join points have different requirements. Method and + constructor call join points can be advised only if ajc controls + the bytecode for the caller. Field reference or assignment join + points can be advised only if ajc controls the bytecode for the + "caller", the code actually making the reference or assignment. + Initialization join points can be advised only if ajc controls the + bytecode of the type being initialized, and execution join points + can be advised only if ajc controls the bytecode for the method or + constructor body in question. </para> <para> - Aspects that are defined <literal>perthis</literal> or - <literal>pertarget</literal> also have restrictions based on control of the - code. In particular, at a join point where the source code for the - currently executing object is not available, an aspect defined - <literal>perthis</literal> of that join point will not be associated. So - aspects defined <literal>perthis(Object)</literal> will not create aspect - instances for every object, just those whose class the compiler controls. - Similar restrictions apply to <literal>pertarget</literal> aspects. + Aspects that are defined <literal>perthis</literal> or + <literal>pertarget</literal> also have restrictions based on + control of the code. In particular, at a join point where the + bytecode for the currently executing object is not available, an + aspect defined <literal>perthis</literal> of that join point will + not be associated. So aspects defined + <literal>perthis(Object)</literal> will not create aspect + instances for every object unless <literal>Object</literal>is part + of the compile. Similar restrictions apply to + <literal>pertarget</literal> aspects. </para> <para> - Inter-type declarations such as <literal>declare parents</literal> also have - restrictions based on control of the code. If the code for the target of an - inter-type declaration is not available, then the inter-type declaration is - not made on that target. So, <literal>declare parents : String implements - MyInterface</literal> will not work for - <literal>java.lang.String</literal>. + Inter-type declarations such as <literal>declare parents</literal> + also have restrictions based on control of the code. If the + bytecode for the target of an inter-type declaration is not + available, then the inter-type declaration is not made on that + target. So, <literal>declare parents : String implements + MyInterface</literal> will not work for + <literal>java.lang.String</literal> unless + <literal>java.lang.String</literal> is part of the compile. </para> <para> - Other AspectJ implementations, indeed, future versions of ajc, may define - <emphasis>code the implementation controls</emphasis> more liberally. + Other AspectJ implementations, indeed, future versions of ajc, may + define <emphasis>code the implementation controls</emphasis> more + liberally or restrictively. </para> <para> - Control may mean that classes need only be available in classfile or jarfile - format. So, even if Client.java and Point.java were precompiled, their join - points could still be advised. In such a system, though, it might still be - the case that join points from code of system libraries such as java.lang - could not be advised. - </para> - - <para> - Or control could even include system libraries, thus allowing a call join - point from java.util.Hashmap to java.lang.Object to be advised. - </para> - - <para> - All AspectJ implementations are required to control the code of the - files that the compiler compiles itself. - </para> - - <para> - The important thing to remember is that core concepts of AspectJ, - such as the join point, are unchanged, regardless of which - implementation is used. During your development, you will have to - be aware of the limitations of the ajc compiler you're using, but - these limitations should not drive the design of your aspects. + The important thing to remember is that core concepts of AspectJ, + such as the join point, are unchanged, regardless of which + implementation is used. During your development, you will have to + be aware of the limitations of the ajc compiler you're using, but + these limitations should not drive the design of your aspects. </para> </appendix> - -<!-- Local variables: --> -<!-- fill-column: 79 --> -<!-- sgml-local-ecat-files: progguide.ced --> -<!-- sgml-parent-document:("progguide.sgml" "book" "appendix") --> -<!-- End: --> diff --git a/docs/progGuideDB/pitfalls.xml b/docs/progGuideDB/pitfalls.xml index 5379d5daa..daf08f801 100644 --- a/docs/progGuideDB/pitfalls.xml +++ b/docs/progGuideDB/pitfalls.xml @@ -1,19 +1,22 @@ <chapter id="pitfalls" xreflabel="Pitfalls"> <title>Pitfalls</title> - <sect1><!-- About this Chapter --> - <title>About this Chapter</title> + <sect1 id="pitfalls-intro"> + <title>Introduction</title> - <para>This chapter consists of aspectj programs that may lead to surprising - behaviour and how to understand them. + <para> + This chapter consists of a few AspectJ programs that may lead to + surprising behavior and how to understand them. </para> </sect1> - <sect1> + <sect1 id="pitfalls-infiniteLoops"> <title>Infinite loops</title> - <para>Here is a Java program with peculiar behavior </para> + <para> + Here is a Java program with peculiar behavior + </para> <programlisting><![CDATA[ public class Main { @@ -32,16 +35,21 @@ public class Main { } ]]></programlisting> - <para>This program will never reach the println call, but when it aborts - will have no stack trace. </para> + <para> + This program will never reach the println call, but when it aborts + may have no stack trace. + </para> - <para>This silence is caused by multiple StackOverflowExceptions. First - the infinite loop in the body of the method generates one, which the - finally clause tries to handle. But this finally clause also generates an - infinite loop which the current JVMs can't handle gracefully leading to the - completely silent abort. </para> + <para> + This silence is caused by multiple StackOverflowExceptions. First + the infinite loop in the body of the method generates one, which the + finally clause tries to handle. But this finally clause also + generates an infinite loop which the current JVMs can't handle + gracefully leading to the completely silent abort. + </para> - <para> The following short aspect will also generate this behavior: + <para> + The following short aspect will also generate this behavior: </para> <programlisting><![CDATA[ @@ -51,9 +59,11 @@ aspect A { } ]]></programlisting> - <para>Why? Because the call to println is also a call matched by the - pointcut <literal>call (* *(..))</literal>. We get no output because we - used simple after() advice. If the aspect were changed to</para> + <para> + Why? Because the call to println is also a call matched by the + pointcut <literal>call (* *(..))</literal>. We get no output because + we used simple after() advice. If the aspect were changed to + </para> <programlisting><![CDATA[ aspect A { @@ -62,13 +72,17 @@ aspect A { } ]]></programlisting> - <para>Then at least a StackOverflowException with a stack trace would be - seen. In both cases, though, the overall problem is advice applying within - its own body. </para> + <para> + Then at least a StackOverflowException with a stack trace would be + seen. In both cases, though, the overall problem is advice applying + within its own body. + </para> - <para>There's a simple idiom to use if you ever have a worry that your - advice might apply in this way. Just restrict the advice from occurring in - join points caused within the aspect. So: </para> + <para> + There's a simple idiom to use if you ever have a worry that your + advice might apply in this way. Just restrict the advice from occurring in + join points caused within the aspect. So: + </para> <programlisting><![CDATA[ aspect A { @@ -77,8 +91,10 @@ aspect A { } ]]></programlisting> - <para>Other solutions might be to more closely restrict the pointcut in - other ways, for example: </para> + <para> + Other solutions might be to more closely restrict the pointcut in + other ways, for example: + </para> <programlisting><![CDATA[ aspect A { @@ -87,17 +103,10 @@ aspect A { } ]]></programlisting> - <para>The moral of the story is that unrestricted generic pointcuts can - pick out more join points than intended. </para> + <para> + The moral of the story is that unrestricted generic pointcuts can + pick out more join points than intended. + </para> </sect1> </chapter> - -<!-- -Local variables: -compile-command: "java sax.SAXCount -v progguide.xml && java com.icl.saxon.StyleSheet -w0 progguide.xml progguide.html.xsl" -fill-column: 79 -sgml-local-ecat-files: "progguide.ced" -sgml-parent-document:("progguide.xml" "book" "chapter") -End: ---> diff --git a/docs/progGuideDB/preface.xml b/docs/progGuideDB/preface.xml index d4a7022d1..1ad7b382b 100644 --- a/docs/progGuideDB/preface.xml +++ b/docs/progGuideDB/preface.xml @@ -1,52 +1,66 @@ -<preface> - <title>Preface</title> - +<preface id="preface"> + <title>Preface</title> + <para> - This user's guide does three things. It + This programming guide does three things. It + <itemizedlist spacing="compact"> <listitem> - <para>introduces the AspectJ language</para> - </listitem> + <para>introduces the AspectJ language</para> + </listitem> <listitem> - <para> - defines each of AspectJ's constructs and their semantics, and</para> + <para> + defines each of AspectJ's constructs and their semantics, and + </para> </listitem> <listitem> - <para> - provides examples of their use.</para> + <para> + provides examples of their use. + </para> </listitem> </itemizedlist> - Appendices give a quick reference and a more formal definition of - AspectJ. + + It includes appendices that give a reference to the syntax of AspectJ, + a more formal description of AspectJ's semantics, and a description of + limitations allowed by AspectJ implementations. </para> - <para>The first section, <xref linkend="gettingstarted" />, provides a gentle - overview of writing AspectJ programs. It also shows how one can introduce - AspectJ into an existing development effort in stages, reducing the - associated risk. You should read this section if this is your first - exposure to AspectJ and you want to get a sense of what AspectJ is all - about.</para> - - <para>The second section, <xref linkend="aspectjlanguage" />, covers the - features of the language in more detail, using code snippets as examples. - The entire language is covered, and after reading this section, you should - be able to use all the features of the language correctly.</para> - - <para>The next section, <xref linkend="examples" />, comprises a set of - complete programs that not only show the features being used, but also try - to illustrate recommended practice. You should read this section after you - are familiar with the elements of AspectJ.</para> - - <para>The back matter contains several appendices that cover AspectJ's - semantics, a quick reference to the language, a glossary of terms and the - index.</para> + <para> + The first section, <xref linkend="starting" />, provides a gentle + overview of writing AspectJ programs. It also shows how one can + introduce AspectJ into an existing development effort in stages, + reducing the associated risk. You should read this section if this is + your first exposure to AspectJ and you want to get a sense of what + AspectJ is all about. + </para> -</preface> + <para> + The second section, <xref linkend="language" />, covers the features of + the language in more detail, using code snippets as examples. All the + basics of the language is covered, and after reading this section, you + should be able to use the language correctly. + </para> -<!-- Local variables: --> -<!-- sgml-local-ecat-files: progguide.ced --> -<!-- sgml-parent-document:("progguide.sgml" "book" "preface") --> -<!-- End: --> + <para> + The next section, <xref linkend="examples" />, comprises a set of + complete programs that not only show the features being used, but also + try to illustrate recommended practice. You should read this section + after you are familiar with the elements of AspectJ. + </para> + + <para> + Finally, there are two short chapters, one on <xref linkend="idioms" /> + and one on <xref linkend="pitfalls" />. + </para> + <para> + The back matter contains several appendices that cover a <xref + linkend="quick">quick reference</xref> to the language's syntax, a more + in depth coverage of its <xref linkend="semantics">semantics</xref>, + and a description of the latitude enjoyed by its <xref + linkend="limitations">implementations</xref>. + </para> + +</preface> diff --git a/docs/progGuideDB/progguide.xml b/docs/progGuideDB/progguide.xml index 405d7267d..f23ca03b3 100644 --- a/docs/progGuideDB/progguide.xml +++ b/docs/progGuideDB/progguide.xml @@ -3,7 +3,6 @@ <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" "../../lib/docbook/docbook-dtd/docbookx.dtd" [ - <!ENTITY preface SYSTEM "preface.xml"> <!ENTITY gettingstarted SYSTEM "gettingstarted.xml"> <!ENTITY language SYSTEM "language.xml"> @@ -13,43 +12,38 @@ <!ENTITY quickreference SYSTEM "quickreference.xml"> <!ENTITY semantics SYSTEM "semantics.xml"> <!ENTITY limitations SYSTEM "limitations.xml"> -<!-- <!ENTITY glossary SYSTEM "glossary.xml"> --> -<!-- <!ENTITY bibliography SYSTEM "bibliography.xml"> --> -<!ENTITY index SYSTEM "index.xml"> - -<!ENTITY % early "ignore"> - ]> <book> <bookinfo> - <title>The AspectJ<superscript>TM</superscript> Programming Guide</title> + <title>The AspectJ<superscript>TM</superscript> Programming Guide</title> <authorgroup> <author> - <othername>the AspectJ Team</othername> + <othername>the AspectJ Team</othername> </author> </authorgroup> - <legalnotice> - <para>Copyright (c) 1998-2001 Xerox Corporation, - 2002-2003 Palo Alto Research Center, Incorporated. - All rights reserved. - </para> - </legalnotice> + <legalnotice> + <para> + Copyright (c) 1998-2001 Xerox Corporation, + 2002-2003 Palo Alto Research Center, Incorporated. + All rights reserved. + </para> + </legalnotice> <abstract> <para> - This programming guide describes the AspectJ language. A - companion guide describes the tools which are part of the - AspectJ development environment. + This programming guide describes the AspectJ language. A + companion guide describes the tools which are part of the + AspectJ development environment. </para> <para> - If you are completely new to AspectJ, you should first read - <xref linkend="gettingstarted"/> for a broad overview of programming + If you are completely new to AspectJ, you should first read + <xref linkend="starting"/> for a broad overview of programming in AspectJ. If you are already familiar with AspectJ, but want a deeper - understanding, you should read <xref linkend="aspectjlanguage"/> and + understanding, you should read <xref linkend="language"/> and look at the examples in the chapter. If you want a more formal definition of AspectJ, you should read <xref linkend="semantics"/>. </para> @@ -60,24 +54,10 @@ &gettingstarted; &language; &examples; - &idioms; + &idioms; &pitfalls; &quickreference; &semantics; &limitations; -<!-- &glossary; --> -<!-- &bibliography; --> -<!-- &index; --> - - </book> - -<!-- -Local Variables: -compile-command: "java com.icl.saxon.StyleSheet -w0 progguide.xml progguide.html.xsl" -fill-column: 79 -sgml-indent-step: 3 -sgml-local-ecat-files: "progguide.ced" -End: ---> diff --git a/docs/progGuideDB/quickreference.xml b/docs/progGuideDB/quickreference.xml index 4f72dbb7c..6a5d83052 100644 --- a/docs/progGuideDB/quickreference.xml +++ b/docs/progGuideDB/quickreference.xml @@ -1,687 +1,773 @@ -<appendix id="quickreference" xreflabel="AspectJ Quick Reference"> - +<appendix id="quick" xreflabel="AspectJ Quick Reference"> <title>AspectJ Quick Reference</title> - <indexterm><primary>AspectJ</primary><secondary>semantics</secondary> - <tertiary>quick reference</tertiary> - </indexterm> - - <sect1> - <title>Pointcut Designators</title> - - <table frame="all" id="qrpointcutdesignators"> - <title>Pointcut Designators</title> - - <tgroup cols="2" align="left"> - <colspec colname="c1"/> - <colspec colname="c2"/> - <spanspec spanname="hspan" namest="c1" nameend="c2" align="left"/> - - <tbody valign="middle"> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Methods and Constructors</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>call(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Method or constructor call join points when the signature - matches <replaceable>Signature</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>execution(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Method or constructor execution join points when the - signature matches - <replaceable>Signature</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>initialization(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Object initialization join point when the first - constructor called in the type matches - <replaceable>Signature</replaceable> - </entry> - </row> - <row> - <entry> - <literal>preinitialization(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Object pre-initialization join point when the first constructor - called in the type matches <replaceable>Signature</replaceable> - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Exception Handlers</emphasis> - </entry> - </row> - - <row rowsep="1"> - <entry> - <literal>handler(<replaceable>TypePattern</replaceable>)</literal> - </entry> - <entry> - Exception handler execution join points when - try handlers for the throwable types in - <replaceable>TypePattern</replaceable> are executed. - The exception object can be accessed with an - <literal>args</literal> pointcut. - </entry> - </row> - <row> - <entry spanname="hspan"> - <emphasis role="bold">Advice</emphasis> - </entry> - </row> - - <row rowsep="1"> - <entry> - <literal>adviceexecution()</literal> - </entry> - <entry> - All advice execution join points. - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Fields</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>get(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Field reference join points when the field matches - <replaceable>Signature</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>set(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Field assignment join points when the field matches - <replaceable>Signature</replaceable>. The new value - can be accessed with an <literal>args</literal> - pointcut. - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Static Initializers</emphasis> - </entry> - </row> - - <row rowsep="1"> - <entry> - <literal>staticinitialization(<replaceable>TypePattern</replaceable>)</literal> - </entry> - <entry> - Static initializer execution join points for the types in - <replaceable>TypePattern</replaceable>. - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Objects</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>this(<replaceable>Type</replaceable>)</literal> - </entry> - <entry> - Join points when the currently executing object is an - instance of <replaceable>Type</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>target(<replaceable>Type</replaceable>)</literal> - </entry> - <entry> - Join points when the target object is an instance - of <replaceable>Type</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>args(<replaceable>Type</replaceable>, ...)</literal> - </entry> - <entry> - Join points when the argument objects are instances of - the <replaceable>Type</replaceable>s - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Lexical Extents</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>within(<replaceable>TypePattern</replaceable>)</literal> - </entry> - <entry> - Join points when the code executing is defined in the - types in <replaceable>TypePattern</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>withincode(<replaceable>Signature</replaceable>)</literal> - </entry> - <entry> - Join points when the code executing is defined in the - method or constructor with signature - <replaceable>Signature</replaceable> - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Control Flow</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>cflow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - Join points in the control flow of the join points - specified by <replaceable>Pointcut</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>cflowbelow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - Join points in the control flow below the join points - specified by <replaceable>Pointcut</replaceable> - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Conditional</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>if(<replaceable>Expression</replaceable>)</literal> - </entry> - <entry> - Join points when the boolean - <replaceable>Expression</replaceable> evaluates - to <literal>true</literal> - </entry> - </row> - - <row> - <entry spanname="hspan"> - <emphasis role="bold">Combination</emphasis> - </entry> - </row> - - <row> - <entry> - <literal>! <replaceable>Pointcut</replaceable></literal> - </entry> - <entry> - Join points that are not picked out by - <replaceable>Pointcut</replaceable> - </entry> - </row> - - <row> - <entry> - <literal><replaceable>Pointcut0</replaceable> <![CDATA[&&]]> <replaceable>Pointcut1</replaceable></literal> - </entry> - <entry> - Join points that are picked out by both - <replaceable>Pointcut0</replaceable> and - <replaceable>Pointcut1</replaceable> - </entry> - </row> - - <row> - <entry> - <literal><replaceable>Pointcut0</replaceable> || <replaceable>Pointcut1</replaceable></literal> - </entry> - <entry> - Join points that are picked out by either - <replaceable>Pointcut0</replaceable> or - <replaceable>Pointcut1</replaceable> - </entry> - </row> - - <row> - <entry> - <literal>( <replaceable>Pointcut</replaceable> )</literal> - </entry> - <entry> - Join points that are picked out by the parenthesized - <replaceable>Pointcut</replaceable> - </entry> - </row> - - </tbody> - </tgroup> - - </table> - - </sect1> - - <sect1> - <title>Type Patterns</title> - <para> - </para> - - <table frame="all" id="qrtypenamepatterns"> - <title>Type Name Patterns</title> - <tgroup cols="2" colsep="1" rowsep="0"> - <tbody> - <row> - <entry><literal>*</literal> alone</entry> - <entry>all types</entry> - </row> - <row> - <entry><literal>*</literal> in an identifier</entry> - <entry>any sequence of characters, not including "."</entry> - </row> - <row> - <entry><literal>..</literal> in an identifier</entry> - <entry>any sequence of characters starting and ending - with "."</entry> - </row> - </tbody> - </tgroup> - </table> - - <para> - The + wildcard can be appended to a type name pattern to - indicate all subtypes. - </para> - - <para> - Any number of []s can be put on a type name or subtype pattern - to indicate array types. - </para> - - <table frame="all" id="qrtypepatterns"> - <title>Type Patterns</title> - <tgroup cols="2" colsep="1" rowsep="0"> - <tbody> - <row> - <entry><replaceable>TypeNamePattern</replaceable></entry> - <entry>all types in <replaceable>TypeNamePattern</replaceable></entry> - </row> - <row> - <entry><replaceable>SubtypePattern</replaceable></entry> - <entry>all types in <replaceable>SubtypePattern</replaceable>, a - pattern with a +. </entry> - </row> - <row> - <entry><replaceable>ArrayTypePattern</replaceable></entry> - <entry>all types in <replaceable>ArrayTypePattern</replaceable>, - a pattern with one or more []s. </entry> - </row> - <row> - <entry><literal>!<replaceable>TypePattern</replaceable></literal></entry> - <entry>all types not in <replaceable>TypePattern</replaceable></entry> - </row> - <row> - <entry><literal><replaceable>TypePattern0</replaceable> - <![CDATA[&&]]> <replaceable>TypePattern1</replaceable></literal></entry> - <entry>all types in both - <replaceable>TypePattern0</replaceable> and <replaceable>TypePattern1</replaceable></entry> - </row> - <row> - <entry><literal><replaceable>TypePattern0</replaceable> || <replaceable>TypePattern1</replaceable></literal></entry> - <entry>all types in either - <replaceable>TypePattern0</replaceable> or <replaceable>TypePattern1</replaceable></entry> - </row> - <row> - <entry><literal>( <replaceable>TypePattern</replaceable> )</literal></entry> - <entry>all types in <replaceable>TypePattern</replaceable></entry> - </row> - </tbody> - </tgroup> - </table> - - </sect1> - - <sect1> - <title>Advice</title> - - <para></para> - <table frame="all" id="qradvice"> - <title>Advice</title> - <tgroup cols="2" colsep="1" rowsep="0"> - <tbody> - - <row> - <entry> - <literal>before(<replaceable>Formals</replaceable>) : </literal> - </entry> - <entry> - Run before the join point. - </entry> - </row> - - - <row> - <entry> - <literal>after(<replaceable>Formals</replaceable>) returning - [ (<replaceable>Formal</replaceable>) ] : </literal> - </entry> - <entry> - Run after the join point if it returns normally. The - optional formal gives access to the returned value. - </entry> - </row> - - <row> - <entry> - <literal>after(<replaceable>Formals</replaceable>) throwing [ - (<replaceable>Formal</replaceable>) ] : </literal> - </entry> - <entry> - Run after the join point if it throws an exception. The - optional formal gives access to the - <literal>Throwable</literal> exception value. - </entry> - </row> - - <row> - <entry> - <literal>after(<replaceable>Formals</replaceable>) : </literal> - </entry> - <entry> - Run after the join point both when it returns normally and - when it throws an exception. - </entry> - </row> - - <row> - <entry> + + <sect1 id="quick-pointcuts"> + <title>Pointcuts</title> + + <informaltable frame="none"> + <tgroup cols="2" align="left"> + <colspec colname="c1"/> + <colspec colname="c2"/> + + <tbody valign="top"> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Methods and Constructors</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>call(<replaceable>Signature</replaceable>)</literal> + </entry> + + <entry> + every call to any method or constructor matching + <replaceable>Signature</replaceable> at the call site + </entry> + </row> + + <row> + <entry> + <literal>execution(<replaceable>Signature</replaceable>)</literal> + </entry> + + <entry> + every execution of any method or constructor matching + <replaceable>Signature</replaceable> + </entry> + </row> + + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Fields</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>get(<replaceable>Signature</replaceable>)</literal> + </entry> + <entry> + every reference to any field matching <replaceable>Signature</replaceable> + </entry> + </row> + + <row> + <entry> + <literal>set(<replaceable>Signature</replaceable>)</literal> + </entry> + <entry> + every assignment to any field matching + <replaceable>Signature</replaceable>. The assigned value can + be exposed with an <literal>args</literal> pointcut + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Exception Handlers</emphasis> + </entry> + </row> + + <row rowsep="1"> + <entry> + <literal>handler(<replaceable>TypePattern</replaceable>)</literal> + </entry> + <entry> + every exception handler for any <literal>Throwable</literal> + type in <replaceable>TypePattern</replaceable>. The exception + value can be exposed with an <literal>args</literal> pointcut + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Advice</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>adviceexecution()</literal> + </entry> + <entry> + every execution of any piece of advice + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Initialization</emphasis> + </entry> + </row> + + <row rowsep="1"> + <entry> + <literal>staticinitialization(<replaceable>TypePattern</replaceable>)</literal> + </entry> + <entry> + every execution of a static initializer for any type in + <replaceable>TypePattern</replaceable> + </entry> + </row> + + <row> + <entry> + <literal>initialization(<replaceable>Signature</replaceable>)</literal> + </entry> + <entry> + every initialization of an object when the first constructor + called in the type matches + <replaceable>Signature</replaceable>, encompassing the return + from the super constructor call to the return of the + first-called constructor + </entry> + </row> + <row> + <entry> + <literal>preinitialization(<replaceable>Signature</replaceable>)</literal> + </entry> + <entry> + every pre-initialization of an object when the first + constructor called in the type matches + <replaceable>Signature</replaceable>, encompassing the entry + of the first-called constructor to the call to the super + constructor + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Lexical</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>within(<replaceable>TypePattern</replaceable>)</literal> + </entry> + <entry> + every join point from code defined in a type in + <replaceable>TypePattern</replaceable> + </entry> + </row> + + <row> + <entry> + <literal>withincode(<replaceable>Signature</replaceable>)</literal> + </entry> + <entry> + every join point from code defined in a method or constructor + matching <replaceable>Signature</replaceable> + </entry> + </row> + </tbody> + </tgroup> + + <tgroup cols="2" align="left"> + <colspec colname="c1"/> + <colspec colname="c2"/> + <tbody valign="top"> + <row> + <entry namest="c1" nameend="c2" > + <emphasis role="bold">Instanceof checks and context exposure</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>this(<replaceable>Type</replaceable> or <replaceable>Id</replaceable>)</literal> + </entry> + <entry> + every join point when the currently executing object is an + instance of <replaceable>Type</replaceable> or + <replaceable>Id</replaceable>'s type + </entry> + </row> + + <row> + <entry> + <literal>target(<replaceable>Type</replaceable> or <replaceable>Id</replaceable>)</literal> + </entry> + <entry> + every join point when the target executing object is an + instance of <replaceable>Type</replaceable> or + <replaceable>Id</replaceable>'s type + </entry> + </row> + + <row> + <entry> + <literal>args(<replaceable>Type</replaceable> or + <replaceable>Id</replaceable>, ...)</literal> + </entry> + <entry> + every join point when the arguments are instances of + <replaceable>Type</replaceable>s or the types of the + <replaceable>Id</replaceable>s + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Control Flow</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>cflow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + every join point in the control flow of each join point + <replaceable>P</replaceable> picked out by + <replaceable>Pointcut</replaceable>, including + <replaceable>P</replaceable> itself + </entry> + </row> + + <row> + <entry> + <literal>cflowbelow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + every join point below the control flow of each join point + <replaceable>P</replaceable> picked out by + <replaceable>Pointcut</replaceable>; does not include + <replaceable>P</replaceable> itself + </entry> + </row> + + <!-- ===== --> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Conditional</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>if(<replaceable>Expression</replaceable>)</literal> + </entry> + <entry> + every join point when the boolean + <replaceable>Expression</replaceable> is + <literal>true</literal> + </entry> + </row> + </tbody> + </tgroup> + + <tgroup cols="2" align="left"> + <colspec colname="c1"/> + <colspec colname="c2"/> + + <tbody valign="top"> + <row> + <entry namest="c1" nameend="c2"> + <emphasis role="bold">Combination</emphasis> + </entry> + </row> + + <row> + <entry> + <literal>! <replaceable>Pointcut</replaceable></literal> + </entry> + <entry> + every join point not picked out by + <replaceable>Pointcut</replaceable> + </entry> + </row> + + <row> + <entry> + <literal><replaceable>Pointcut0</replaceable> <![CDATA[&&]]> <replaceable>Pointcut1</replaceable></literal> + </entry> + <entry> + each join point picked out by both + <replaceable>Pointcut0</replaceable> and + <replaceable>Pointcut1</replaceable> + </entry> + </row> + + <row> + <entry> + <literal><replaceable>Pointcut0</replaceable> || <replaceable>Pointcut1</replaceable></literal> + </entry> + <entry> + each join point picked out by either + <replaceable>Pointcut0</replaceable> or + <replaceable>Pointcut1</replaceable> + </entry> + </row> + + <row> + <entry> + <literal>( <replaceable>Pointcut</replaceable> )</literal> + </entry> + <entry> + each join point picked out by + <replaceable>Pointcut</replaceable> + </entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect1> + +<!-- ============================== --> + + <sect1 id="quick-typePatterns"> + <title>Type Patterns</title> + + <para> + A type pattern is one of + </para> + + <informaltable frame="none"> + <tgroup cols="2" > + <tbody valign="top"> + <row> + <entry><replaceable>TypeNamePattern</replaceable></entry> + <entry>all types in <replaceable>TypeNamePattern</replaceable></entry> + </row> + <row> + <entry><replaceable>SubtypePattern</replaceable></entry> + <entry>all types in <replaceable>SubtypePattern</replaceable>, a + pattern with a +. </entry> + </row> + <row> + <entry><replaceable>ArrayTypePattern</replaceable></entry> + <entry>all types in <replaceable>ArrayTypePattern</replaceable>, + a pattern with one or more []s. </entry> + </row> + <row> + <entry><literal>!<replaceable>TypePattern</replaceable></literal></entry> + <entry>all types not in <replaceable>TypePattern</replaceable></entry> + </row> + <row> + <entry><literal><replaceable>TypePattern0</replaceable> + <![CDATA[&&]]> <replaceable>TypePattern1</replaceable></literal></entry> + <entry>all types in both + <replaceable>TypePattern0</replaceable> and <replaceable>TypePattern1</replaceable></entry> + </row> + <row> + <entry><literal><replaceable>TypePattern0</replaceable> || <replaceable>TypePattern1</replaceable></literal></entry> + <entry>all types in either + <replaceable>TypePattern0</replaceable> or <replaceable>TypePattern1</replaceable></entry> + </row> + <row> + <entry><literal>( <replaceable>TypePattern</replaceable> )</literal></entry> + <entry>all types in <replaceable>TypePattern</replaceable></entry> + </row> + </tbody> + </tgroup> + </informaltable> + + <para> + where <replaceable>TypeNamePattern</replaceable> can either be a + plain type name, the wildcard <literal>*</literal> (indicating all + types), or an identifier with embedded <literal>*</literal> and + <literal>..</literal> wildcards. + </para> + + <para> + An embedded <literal>*</literal> in an identifier matches any + sequence of characters, but does not match the package (or + inner-type) separator ".". + </para> + + <para> + An embedded <literal>..</literal> in an identifier matches any + sequence of characters that starts and ends with the package (or + inner-type) separator ".". + </para> + </sect1> + +<!-- ============================== --> + + <sect1 id="quick-advice"> + <title>Advice</title> + + <para> + Each piece of advice is of the form + + <blockquote> + <literal>[ strictfp ] <replaceable>AdviceSpec</replaceable> + [ throws <replaceable>TypeList</replaceable> ] : + <replaceable>Pointcut</replaceable> { + <replaceable>Body</replaceable> } </literal> + </blockquote> + + where <replaceable>AdviceSpec</replaceable> is one of + </para> + + <variablelist> + <varlistentry> + <term> + <literal>before( <replaceable>Formals</replaceable> ) </literal> + </term> + <listitem> + runs before each join point + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>after( <replaceable>Formals</replaceable> ) returning + [ ( <replaceable>Formal</replaceable> ) ] </literal> + </term> + <listitem> + runs after each join point that returns normally. The + optional formal gives access to the returned value + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>after( <replaceable>Formals</replaceable> ) throwing [ + ( <replaceable>Formal</replaceable> ) ] </literal> + </term> + <listitem> + runs after each join point that throws a + <literal>Throwable</literal>. If the optional formal is + present, runs only after each join point that throws a + <literal>Throwable</literal> of the type of + <replaceable>Formal</replaceable>, and + <replaceable>Formal</replaceable> gives access to the + <literal>Throwable</literal> exception value + </listitem> + </varlistentry> + <varlistentry> + <term> + <literal>after( <replaceable>Formals</replaceable> ) </literal> + </term> + <listitem> + runs after each join point regardless of whether it returns + normally or throws a <literal>Throwable</literal> + </listitem> + </varlistentry> + + <varlistentry> + <term> <literal><replaceable>Type</replaceable> - around(<replaceable>Formals</replaceable>) [ throws - <replaceable>TypeList</replaceable> ] :</literal> - </entry> - <entry> - Run instead of the join point. The join point can be - executed by calling <literal>proceed</literal>. - </entry> - </row> - - </tbody> - </tgroup> - </table> - </sect1> - - <sect1> - <title>Inter-type declarations</title> - <para> - </para> - - <table frame="all" id="qrintroduction"> - <title>Inter-type declarations</title> - - <tgroup cols="2" colsep="1" rowsep="0"> - - <tbody> - - <row> - <entry> - <replaceable>Modifiers ReturnType OnType . Id(Formals) { Body }</replaceable> - </entry> - <entry> - Defines a method on <replaceable>OnType</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal>abstract <replaceable>Modifiers ReturnType OnType . Id(Formals)</replaceable>;</literal> - </entry> - <entry> - Defines an abstract method on <replaceable>OnType</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal><replaceable>Modifiers OnType</replaceable>.new<replaceable>(Formals) { Body }</replaceable></literal> - </entry> - <entry> - Defines a a constructor on <replaceable>OnType</replaceable>. - </entry> - </row> - - <row> - <entry> - <replaceable>Modifiers Type OnType.Id [ = Expression ];</replaceable> - </entry> - <entry> - Defines a field on <replaceable>OnType</replaceable>. - </entry> - </row> - </tbody> - </tgroup> - </table> - - </sect1> - - <sect1> - <title>Other declarations</title> - <para> - </para> - - <table frame="all" id="qrotherdeclarations"> - <title>Other declarations</title> - - <tgroup cols="2" colsep="1" rowsep="0"> - - <tbody> - - <row> - <entry> - <literal>declare parents: <replaceable>TypePattern</replaceable> extends <replaceable>TypeList</replaceable>;</literal> - </entry> - <entry> - Declares that the types in <replaceable>TypePattern</replaceable> extend the types of <replaceable>TypeList</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal>declare parents: <replaceable>TypePattern</replaceable> implements <replaceable>TypeList</replaceable>;</literal> - </entry> - <entry> - Declares that the types in <replaceable>TypePattern</replaceable> implement the types of <replaceable>TypeList</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal>declare warning: <replaceable>Pointcut</replaceable>: <replaceable>String</replaceable>;</literal> - </entry> - <entry> - Declares that if any of the join points in - <replaceable>Pointcut</replaceable> possibly exist in - the program, the compiler should emit a warning of - <replaceable>String</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal>declare error: <replaceable>Pointcut</replaceable>: <replaceable>String</replaceable>;</literal> - </entry> - <entry> - Declares that if any of the join points in - <replaceable>Pointcut</replaceable> possibly exist in - the program, the compiler should emit an error of - <replaceable>String</replaceable>. - </entry> - </row> - - <row> - <entry> - <literal>declare soft: - <replaceable>TypePattern</replaceable>: - <replaceable>Pointcut</replaceable>; </literal> - </entry> - <entry> - Declares that any exception of a type in - <replaceable>TypePattern</replaceable> that gets - thrown at any join point picked out by - <replaceable>Pointcut</replaceable> will be wrapped in - <literal>org.aspectj.lang.SoftException</literal>. - </entry> - </row> - <row> - <entry> - <literal>declare precedence: - <replaceable>TypePatternList</replaceable> ; </literal> - </entry> - <entry> - Declares that at any join point where multiple pieces of advice - apply, the advice precedence at that join point is in - <replaceable>TypePatternList</replaceable> order. - </entry> - </row> - - </tbody> - </tgroup> - </table> - - </sect1> - - <sect1> - <title>Aspect Associations</title> - <para> - </para> - - <table frame="all" id="qrassociations"> - <title>Associations</title> - <tgroup cols="3" align="left" colsep="1" rowsep="1"> - <thead> - <row> - <entry>modifier</entry> - <entry>Description</entry> - <entry>Accessor</entry> - </row> - </thead> - - <tbody> - - <row> - <entry> - [ <literal>issingleton</literal> ] - </entry> - <entry> - One instance of the aspect is made. This is - the default. - </entry> - <entry> - <literal>aspectOf()</literal> at all join points - </entry> - </row> - - <row> - <entry> - <literal>perthis(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - An instance is associated with each object that is the - currently executing object at any join point in - <replaceable>Pointcut</replaceable>. - </entry> - <entry> - <literal>aspectOf(Object)</literal> at all join points</entry> - </row> - - <row> - <entry> - <literal>pertarget(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - An instance is associated with each object that is the - target object at any join point in - <replaceable>Pointcut</replaceable>. - </entry> - <entry> - <literal>aspectOf(Object)</literal> at all join points</entry> - </row> - - <row> - <entry> - <literal>percflow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - The aspect is defined for each entrance to the control flow of - the join points defined by <replaceable>Pointcut</replaceable>. </entry> - <entry> - <literal>aspectOf()</literal> at join points in - <literal>cflow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - </row> - - <row> - <entry> - <literal>percflowbelow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - <entry> - The aspect is defined for each entrance to the control flow - below the join points defined by <replaceable>Pointcut</replaceable>. - </entry> - <entry> - <literal>aspectOf()</literal> at join points in - <literal>cflowbelow(<replaceable>Pointcut</replaceable>)</literal> - </entry> - </row> - </tbody> - - </tgroup> - </table> - </sect1> + around( <replaceable>Formals</replaceable> ) </literal> + </term> + <listitem> + runs in place of each join point. The join point can be + executed by calling <literal>proceed</literal>, which takes + the same number and types of arguments as the around advice. + </listitem> + </varlistentry> + </variablelist> + + <para> + Three special variables are available inside of advice bodies: + </para> + + <variablelist> + <varlistentry> + <term> + <literal>thisJoinPoint</literal> + </term> + <listitem> + an object of type <ulink + url="../api/org/aspectj/lang/JoinPoint.html"><literal>org.aspectj.lang.JoinPoint</literal></ulink> + representing the join point at which the advice is executing. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>thisJoinPointStaticPart</literal> + </term> + <listitem> + equivalent to <literal>thisJoinPoint.getStaticPart()</literal>, + but may use fewer runtime resources. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>thisEnclosingJoinPointStaticPart</literal> + </term> + <listitem> + the static part of the dynamically enclosing join point. + </listitem> + </varlistentry> + </variablelist> + </sect1> + +<!-- ============================== --> + + <sect1 id="quick-interType"> + <title>Inter-type member declarations</title> + + <para> + Each inter-type member is one of + </para> + + <variablelist> + <varlistentry> + <term> + <literal> + <replaceable>Modifiers ReturnType OnType . Id</replaceable> + ( <replaceable>Formals</replaceable> ) + [ throws <replaceable>TypeList</replaceable> ] + { <replaceable>Body</replaceable> } + </literal> + </term> + <listitem> + a method on <replaceable>OnType</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + abstract <replaceable>Modifiers ReturnType OnType . Id</replaceable> + ( <replaceable>Formals</replaceable> ) + [ throws <replaceable>TypeList</replaceable> ] ; + </literal> + </term> + <listitem> + an abstract method on <replaceable>OnType</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + <replaceable>Modifiers OnType . </replaceable> new + ( <replaceable>Formals</replaceable> ) + [ throws <replaceable>TypeList</replaceable> ] + { <replaceable>Body</replaceable> } + </literal> + </term> + <listitem> + a constructor on <replaceable>OnType</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + <replaceable>Modifiers Type OnType . Id </replaceable> + [ = <replaceable>Expression</replaceable> ] ; + </literal> + </term> + <listitem> + a field on <replaceable>OnType</replaceable>. + </listitem> + </varlistentry> + </variablelist> + </sect1> + +<!-- ============================== --> + + <sect1 id="quick-other"> + <title>Other declarations</title> + + <variablelist> + <varlistentry> + <term> + <literal> + declare parents : + <replaceable>TypePattern</replaceable> extends + <replaceable>Type</replaceable> ; + </literal> + </term> + <listitem> + the types in <replaceable>TypePattern</replaceable> extend + <replaceable>Type</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + declare parents : <replaceable>TypePattern</replaceable> + implements <replaceable>TypeList</replaceable> ; + </literal> + </term> + <listitem> + the types in <replaceable>TypePattern</replaceable> + implement the types in <replaceable>TypeList</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + declare warning : <replaceable>Pointcut</replaceable> : + <replaceable>String</replaceable> ; + </literal> + </term> + <listitem> + if any of the join points in <replaceable>Pointcut</replaceable> + possibly exist in the program, the compiler emits the warning + <replaceable>String</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + declare error : <replaceable>Pointcut</replaceable> : + <replaceable>String</replaceable> ; + </literal> + </term> + <listitem> + if any of the join points in <replaceable>Pointcut</replaceable> + could possibly exist in the program, the compiler emits the + error <replaceable>String</replaceable>. + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal> + declare soft : + <replaceable>Type</replaceable> : + <replaceable>Pointcut</replaceable> ; + </literal> + </term> + <listitem> + any <replaceable>Type</replaceable> exception + that gets thrown at any join point picked out by + <replaceable>Pointcut</replaceable> is wrapped in <ulink + url="../api/org/aspectj/lang/SoftException.html"><literal>org.aspectj.lang.SoftException</literal></ulink>. + </listitem> + </varlistentry> + <varlistentry> + <term> + <literal> + declare precedence : + <replaceable>TypePatternList</replaceable> ; + </literal> + </term> + <listitem> + at any join point where multiple pieces of advice + apply, the advice precedence at that join point is in + <replaceable>TypePatternList</replaceable> order. + </listitem> + </varlistentry> + </variablelist> + </sect1> + +<!-- ============================== --> + + <sect1 id="quick-aspectAssociations"> + <title>Aspects</title> + + <para> + Each aspect is of the form + + <blockquote> + <literal> + [ privileged ] <replaceable>Modifiers</replaceable> + aspect <replaceable>Id</replaceable> + [ extends <replaceable>Type</replaceable> ] + [ implements <replaceable>TypeList</replaceable> ] + [ <replaceable>PerClause</replaceable> ] + { <replaceable>Body</replaceable> } + </literal> + </blockquote> + where <replaceable>PerClause</replaceable> defines how the aspect is + instantiated and associated (<literal>issingleton</literal> by + default): + </para> + + <informaltable frame="none"> + <tgroup cols="3" align="left"> + <thead> + <row> + <entry align="left">PerClause</entry> + <entry align="left">Description</entry> + <entry align="left">Accessor</entry> + </row> + </thead> + + <tbody valign="top"> + <row> + <entry> + [ <literal>issingleton</literal> ] + </entry> + <entry> + One instance of the aspect is made. This is + the default. + </entry> + <entry> + <literal>aspectOf()</literal> at all join points + </entry> + </row> + + <row> + <entry> + <literal>perthis(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + An instance is associated with each object that is the + currently executing object at any join point in + <replaceable>Pointcut</replaceable>. + </entry> + <entry> + <literal>aspectOf(Object)</literal> at all join points + </entry> + </row> + + <row> + <entry> + <literal>pertarget(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + An instance is associated with each object that is the + target object at any join point in + <replaceable>Pointcut</replaceable>. + </entry> + <entry> + <literal>aspectOf(Object)</literal> at all join points + </entry> + </row> + + <row> + <entry> + <literal>percflow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + The aspect is defined for each entrance to the control flow of + the join points defined by <replaceable>Pointcut</replaceable>. </entry> + <entry> + <literal>aspectOf()</literal> at join points in + <literal>cflow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + </row> + + <row> + <entry> + <literal>percflowbelow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + <entry> + The aspect is defined for each entrance to the control flow + below the join points defined by <replaceable>Pointcut</replaceable>. + </entry> + <entry> + <literal>aspectOf()</literal> at join points in + <literal>cflowbelow(<replaceable>Pointcut</replaceable>)</literal> + </entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect1> + </appendix> -<!-- Local variables: --> -<!-- fill-column: 79 --> -<!-- sgml-local-ecat-files: progguide.ced --> -<!-- sgml-parent-document:("progguide.sgml" "book" "appendix") --> -<!-- End: --> diff --git a/docs/progGuideDB/semantics.xml b/docs/progGuideDB/semantics.xml index f137f7497..0bc896254 100644 --- a/docs/progGuideDB/semantics.xml +++ b/docs/progGuideDB/semantics.xml @@ -2,323 +2,300 @@ <title>Language Semantics</title> - <para> - AspectJ extends Java by overlaying a concept of join points onto the - existing Java semantics and adding a few new program elements to Java: - </para> - - <para> - A join point is a well-defined point in the execution of a program. These - include method and constructor calls, field accesses and others described - below. - </para> - - <para> - A pointcut picks out join points, and exposes some of the values in the - execution context of those join points. There are several primitive - pointcut designators, and others can be named and defined by the - <literal>pointcut</literal> declaration. - </para> - - <para> - A piece of advice is code that executes at each join point in a pointcut. Advice has - access to the values exposed by the pointcut. Advice is defined by - <literal>before</literal>, <literal>after</literal>, and - <literal>around</literal> declarations. - </para> - - <para> - Inter-type declarations form AspectJ's static crosscutting features, that - is, is code that may change the type structure of a program, by adding to - or extending interfaces and classes with new fields, constructors, or - methods. Some inter-type declarations are defined through an extension of - usual method, field, and constructor declarations, and other declarations - are made with a new <literal>declare</literal> keyword. - </para> - - <para> - An aspect is a crosscutting type that encapsulates pointcuts, advice, and - static crosscutting features. By type, we mean Java's notion: a modular - unit of code, with a well-defined interface, about which it is possible to - do reasoning at compile time. Aspects are defined by the - <literal>aspect</literal> declaration. - </para> - - <sect1 id="joinPoints"> + <sect1 id="semantics-intro"> + <title>Introduction</title> + + <para> + AspectJ extends Java by overlaying a concept of join points onto the + existing Java semantics and adding a few new program elements to Java: + </para> + + <para> + A join point is a well-defined point in the execution of a + program. These include method and constructor calls, field accesses and + others described below. + </para> + + <para> + A pointcut picks out join points, and exposes some of the values in the + execution context of those join points. There are several primitive + pointcut designators, and others can be named and defined by the + <literal>pointcut</literal> declaration. + </para> + + <para> + A piece of advice is code that executes at each join point in a + pointcut. Advice has access to the values exposed by the + pointcut. Advice is defined by <literal>before</literal>, + <literal>after</literal>, and <literal>around</literal> declarations. + </para> + + <para> + Inter-type declarations form AspectJ's static crosscutting features, + that is, is code that may change the type structure of a program, by + adding to or extending interfaces and classes with new fields, + constructors, or methods. Some inter-type declarations are defined + through an extension of usual method, field, and constructor + declarations, and other declarations are made with a new + <literal>declare</literal> keyword. + </para> + + <para> + An aspect is a crosscutting type that encapsulates pointcuts, advice, + and static crosscutting features. By type, we mean Java's notion: a + modular unit of code, with a well-defined interface, about which it is + possible to do reasoning at compile time. Aspects are defined by the + <literal>aspect</literal> declaration. + </para> + </sect1> + +<!-- ============================== --> + + <sect1 id="semantics-joinPoints"> <title>Join Points</title> <para> While aspects define types that crosscut, the AspectJ system does not - allow completely arbitrary crosscutting. Rather, aspects define types that - cut across principled points in a program's execution. These principled - points are called join points. + allow completely arbitrary crosscutting. Rather, aspects define types + that cut across principled points in a program's execution. These + principled points are called join points. </para> - <para> - A join point is a well-defined point in the execution of a program. The - join points defined by AspectJ are: + A join point is a well-defined point in the execution of a + program. The join points defined by AspectJ are: </para> <variablelist> - <varlistentry> <term>Method call</term> <listitem> - <para> - When a method is called, not including super calls of non-static - methods. - </para> + When a method is called, not including super calls of + non-static methods. </listitem> </varlistentry> <varlistentry> <term>Method execution</term> <listitem> - <para> - When the body of code for an actual method executes. - </para> + When the body of code for an actual method executes. </listitem> </varlistentry> - <varlistentry> <term>Constructor call</term> <listitem> - <para> - When an object is built and that object's initial constructor is - called (i.e., not for "super" or "this" constructor calls). The - object being constructed is returned at a constructor call join - point, so its return type is considered to be the type of the - object, and the object itself may be accessed with <literal>after - returning</literal> advice. - </para> + When an object is built and that object's initial constructor is + called (i.e., not for "super" or "this" constructor calls). The + object being constructed is returned at a constructor call join + point, so its return type is considered to be the type of the + object, and the object itself may be accessed with <literal>after + returning</literal> advice. </listitem> </varlistentry> <varlistentry> <term>Constructor execution</term> <listitem> - <para> - When the body of code for an actual constructor executes, after its - this or super constructor call. The object being constructed is - the currently executing object, and so may be accessed with the - <literal>this</literal> pointcut. No value is returned from - a constructor execution join point, so its return type is - considered to be void. - </para> + When the body of code for an actual constructor executes, after + its this or super constructor call. The object being constructed + is the currently executing object, and so may be accessed with + the <literal>this</literal> pointcut. The constructor execution + join point for a constructor that calls a super constructor also + includes any non-static initializers of enclosing class. No + value is returned from a constructor execution join point, so its + return type is considered to be void. </listitem> </varlistentry> <varlistentry> <term>Static initializer execution</term> <listitem> - <para> - When the static initializer for a class executes. - No value is returned from a static initializer execution join - point, so its return type is considered to be void. - </para> + When the static initializer for a class executes. No value is + returned from a static initializer execution join point, so its + return type is considered to be void. </listitem> </varlistentry> <varlistentry> <term>Object pre-initialization</term> <listitem> - <para> - Before the object initialization code for a particular class runs. - This encompasses the time between the start of its first called - constructor and the start of its parent's constructor. Thus, the - execution of these join points encompass the join points of the - evaluation of the arguments of <literal>this()</literal> and - <literal>super()</literal> constructor calls. - No value is returned from an object pre-initialization join - point, so its return type is considered to be void. - </para> + Before the object initialization code for a particular class runs. + This encompasses the time between the start of its first called + constructor and the start of its parent's constructor. Thus, the + execution of these join points encompass the join points of the + evaluation of the arguments of <literal>this()</literal> and + <literal>super()</literal> constructor calls. No value is + returned from an object pre-initialization join point, so its + return type is considered to be void. </listitem> </varlistentry> <varlistentry> <term>Object initialization</term> <listitem> - <para> - When the object initialization code for a particular class runs. - This encompasses the time between the return of its parent's - constructor and the return of its first called constructor. It - includes all the dynamic initializers and constructors used to - create the object. The object being constructed is - the currently executing object, and so may be accessed with the - <literal>this</literal> pointcut. - No value is returned from a constructor execution join point, so - its return type is considered to be void. - </para> + When the object initialization code for a particular class runs. + This encompasses the time between the return of its parent's + constructor and the return of its first called constructor. It + includes all the dynamic initializers and constructors used to + create the object. The object being constructed is the currently + executing object, and so may be accessed with the + <literal>this</literal> pointcut. No value is returned from a + constructor execution join point, so its return type is + considered to be void. </listitem> </varlistentry> <varlistentry> <term>Field reference</term> <listitem> - <para> - When a non-constant field is referenced. - [Note that references to constant fields (static final - fields bound to a constant string object or primitive value) are not - join points, since Java requires them to be inlined.] - </para> + When a non-constant field is referenced. [Note that references + to constant fields (static final fields bound to a constant + string object or primitive value) are not join points, since Java + requires them to be inlined.] </listitem> </varlistentry> <varlistentry> <term>Field set</term> <listitem> - <para> - When a field is assigned to. - Field set join points are considered to have one argument, - the value the field is being set to. - No value is returned from a field set join point, so - its return type is considered to be void. - [Note that the initializations of constant fields (static - final fields where the initializer is a constant string object or - primitive value) are not join points, since Java requires their - references to be inlined.] - </para> + When a field is assigned to. + Field set join points are considered to have one argument, + the value the field is being set to. + No value is returned from a field set join point, so + its return type is considered to be void. + [Note that the initializations of constant fields (static + final fields where the initializer is a constant string object or + primitive value) are not join points, since Java requires their + references to be inlined.] </listitem> </varlistentry> <varlistentry> <term>Handler execution</term> <listitem> - <para> - When an exception handler executes. - Handler execution join points are considered to have one argument, - the exception being handled. - No value is returned from a field set join point, so - its return type is considered to be void. - </para> + When an exception handler executes. + Handler execution join points are considered to have one argument, + the exception being handled. + No value is returned from a field set join point, so + its return type is considered to be void. </listitem> </varlistentry> <varlistentry> <term>Advice execution</term> <listitem> - <para> - When the body of code for a piece of advice executes. - </para> + When the body of code for a piece of advice executes. </listitem> </varlistentry> </variablelist> - - - - </sect1> <!-- ============================== --> - <sect1 id="pointcuts"> + <sect1 id="semantics-pointcuts"> <title>Pointcuts</title> <para> - A pointcut is a program element that picks out join points and exposes - data from the execution context of those join points. Pointcuts are used - primarily by advice. They can be composed with boolean operators to - build up other pointcuts. The primitive pointcuts and combinators - provided by the language are: + A pointcut is a program element that picks out join points and + exposes data from the execution context of those join points. + Pointcuts are used primarily by advice. They can be composed with + boolean operators to build up other pointcuts. The primitive + pointcuts and combinators provided by the language are: </para> <variablelist> - <varlistentry> <term><literal>call(<replaceable>MethodPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each method call join point whose signature matches - <replaceable>MethodPattern</replaceable>. </para> + Picks out each method call join point whose signature matches + <replaceable>MethodPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>execution(<replaceable>MethodPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each method execution join point whose signature matches - <replaceable>MethodPattern</replaceable>. </para> + Picks out each method execution join point whose signature matches + <replaceable>MethodPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>get(<replaceable>FieldPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each field reference join point whose signature matches + Picks out each field reference join point whose signature matches <replaceable>FieldPattern</replaceable>. [Note that references to constant fields (static final fields bound to a constant string object or primitive value) are not - join points, since Java requires them to be inlined.] </para> + join points, since Java requires them to be inlined.] </listitem> </varlistentry> <varlistentry> <term><literal>set(<replaceable>FieldPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each field set join point whose signature matches + Picks out each field set join point whose signature matches <replaceable>FieldPattern</replaceable>. [Note that the initializations of constant fields (static final fields where the initializer is a constant string object or primitive value) are not join points, since Java requires their - references to be inlined.]</para> + references to be inlined.] </listitem> </varlistentry> - <varlistentry> <term><literal>call(<replaceable>ConstructorPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each constructor call join point whose signature matches - <replaceable>ConstructorPattern</replaceable>. </para> + Picks out each constructor call join point whose signature matches + <replaceable>ConstructorPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>execution(<replaceable>ConstructorPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each constructor execution join point whose signature matches - <replaceable>ConstructorPattern</replaceable>. </para> + Picks out each constructor execution join point whose signature matches + <replaceable>ConstructorPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>initialization(<replaceable>ConstructorPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each object initialization join point whose signature matches - <replaceable>ConstructorPattern</replaceable>. </para> + Picks out each object initialization join point whose signature matches + <replaceable>ConstructorPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>preinitialization(<replaceable>ConstructorPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each object pre-initialization join point whose signature matches - <replaceable>ConstructorPattern</replaceable>. </para> + Picks out each object pre-initialization join point whose signature matches + <replaceable>ConstructorPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>staticinitialization(<replaceable>TypePattern</replaceable>)</literal></term> <listitem> - <para>Picks out each static initializer execution join point whose signature matches - <replaceable>TypePattern</replaceable>. </para> + Picks out each static initializer execution join point whose signature matches + <replaceable>TypePattern</replaceable>. </listitem> </varlistentry> - <varlistentry> <term><literal>handler(<replaceable>TypePattern</replaceable>)</literal></term> <listitem> - <para>Picks out each exception handler join point whose signature matches - <replaceable>TypePattern</replaceable>. </para> + Picks out each exception handler join point whose signature matches + <replaceable>TypePattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>adviceexecution()</literal></term> <listitem> - <para>Picks out all advice execution join points.</para> + Picks out all advice execution join points. </listitem> </varlistentry> @@ -326,151 +303,147 @@ <varlistentry> <term><literal>within(<replaceable>TypePattern</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the executing code is defined - in a type matched by <replaceable>TypePattern</replaceable>. </para> + Picks out each join point where the executing code is defined + in a type matched by <replaceable>TypePattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>withincode(<replaceable>MethodPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the executing code is defined - in a method whose signature matches - <replaceable>MethodPattern</replaceable>. </para> + Picks out each join point where the executing code is defined in + a method whose signature matches + <replaceable>MethodPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>withincode(<replaceable>ConstructorPattern</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the executing code is defined + Picks out each join point where the executing code is defined in a constructor whose signature matches - <replaceable>ConstructorPattern</replaceable>. </para> + <replaceable>ConstructorPattern</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>cflow(<replaceable>Pointcut</replaceable>)</literal></term> <listitem> - <para>Picks out each join point in the control flow of any join point + Picks out each join point in the control flow of any join point <replaceable>P</replaceable> picked out by <replaceable>Pointcut</replaceable>, including - <replaceable>P</replaceable> itself.</para> + <replaceable>P</replaceable> itself. </listitem> </varlistentry> <varlistentry> <term><literal>cflowbelow(<replaceable>Pointcut</replaceable>)</literal></term> <listitem> - <para>Picks out each join point in the control flow of any join point + Picks out each join point in the control flow of any join point <replaceable>P</replaceable> picked out by <replaceable>Pointcut</replaceable>, but not - <replaceable>P</replaceable> itself.</para> + <replaceable>P</replaceable> itself. </listitem> </varlistentry> <varlistentry> <term><literal>this(<replaceable>Type</replaceable> or <replaceable>Id</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the currently executing object + Picks out each join point where the currently executing object (the object bound to <literal>this</literal>) is an instance of <replaceable>Type</replaceable>, or of the type of <replaceable>Id</replaceable> (which must be bound in the enclosing advice or pointcut definition). Will not match any join points from static contexts. - </para> </listitem> </varlistentry> <varlistentry> <term><literal>target(<replaceable>Type</replaceable> or <replaceable>Id</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the target object (the object + Picks out each join point where the target object (the object on which a call or field operation is applied to) is an instance of <replaceable>Type</replaceable>, or of the type of <replaceable>Id</replaceable> (which must be bound in the enclosing advice or pointcut definition). Will not match any calls, gets, or sets of static members. - </para> </listitem> </varlistentry> <varlistentry> <term><literal>args(<replaceable>Type</replaceable> or <replaceable>Id</replaceable>, ...)</literal></term> <listitem> - <para>Picks out each join point where the arguments are instances of - a type of the appropriate type pattern or identifier. </para> + Picks out each join point where the arguments are instances of + a type of the appropriate type pattern or identifier. </listitem> </varlistentry> <varlistentry> <term><literal><replaceable>PointcutId</replaceable>(<replaceable>TypePattern</replaceable> or <replaceable>Id</replaceable>, ...)</literal></term> <listitem> - <para>Picks out each join point that is picked out by the + Picks out each join point that is picked out by the user-defined pointcut designator named by - <replaceable>PointcutId</replaceable>. </para> + <replaceable>PointcutId</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>if(<replaceable>BooleanExpression</replaceable>)</literal></term> <listitem> - <para>Picks out each join point where the boolean expression + Picks out each join point where the boolean expression evaluates to <literal>true</literal>. The boolean expression used can only access static members, variables exposed by teh enclosing pointcut or advice, and <literal>thisJoinPoint</literal> forms. In - particular, it cannot call non-static methods on the aspect. </para> + particular, it cannot call non-static methods on the aspect. </listitem> </varlistentry> <varlistentry> <term><literal>! <replaceable>Pointcut</replaceable></literal></term> <listitem> - <para>Picks out each join point that is not picked out by - <replaceable>Pointcut</replaceable>. </para> + Picks out each join point that is not picked out by + <replaceable>Pointcut</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal><replaceable>Pointcut0</replaceable> <![CDATA[&&]]> <replaceable>Pointcut1</replaceable></literal></term> <listitem> - <para>Picks out each join points that is picked out by both + Picks out each join points that is picked out by both <replaceable>Pointcut0</replaceable> and - <replaceable>Pointcut1</replaceable>. </para> + <replaceable>Pointcut1</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal><replaceable>Pointcut0</replaceable> || <replaceable>Pointcut1</replaceable></literal></term> <listitem> - <para>Picks out each join point that is picked out by either + Picks out each join point that is picked out by either pointcuts. <replaceable>Pointcut0</replaceable> or - <replaceable>Pointcut1</replaceable>. </para> + <replaceable>Pointcut1</replaceable>. </listitem> </varlistentry> <varlistentry> <term><literal>( <replaceable>Pointcut</replaceable> )</literal></term> <listitem> - <para>(parentheses) Picks out each join points picked out by - <replaceable>Pointcut</replaceable>. </para> + Picks out each join points picked out by + <replaceable>Pointcut</replaceable>. </listitem> </varlistentry> </variablelist> <sect2> - <title>Pointcut naming - </title> + <title>Pointcut definition</title> <para> - A named pointcut is defined with the <literal>pointcut</literal> - declaration. + Pointcuts are defined and named by the programmer with the + <literal>pointcut</literal> declaration. </para> - <programlisting> -pointcut publicIntCall(int i): - call(public * *(int)) <![CDATA[&&]]> args(i); + pointcut publicIntCall(int i): + call(public * *(int)) <![CDATA[&&]]> args(i); </programlisting> <para> @@ -481,15 +454,15 @@ pointcut publicIntCall(int i): </para> <programlisting> -class C { - pointcut publicCall(int i): - call(public * *(int)) <![CDATA[&&]]> args(i); -} - -class D { - pointcut myPublicCall(int i): - C.publicCall(i) <![CDATA[&&]]> within(SomeType); -} + class C { + pointcut publicCall(int i): + call(public * *(int)) <![CDATA[&&]]> args(i); + } + + class D { + pointcut myPublicCall(int i): + C.publicCall(i) <![CDATA[&&]]> within(SomeType); + } </programlisting> <para> @@ -499,9 +472,9 @@ class D { </para> <programlisting> -abstract aspect A { - abstract pointcut publicCall(int i); -} + abstract aspect A { + abstract pointcut publicCall(int i); + } </programlisting> <para> @@ -510,67 +483,69 @@ abstract aspect A { </para> <programlisting> -aspect B extends A { - pointcut publicCall(int i): call(public Foo.m(int)) <![CDATA[&&]]> args(i); -} + aspect B extends A { + pointcut publicCall(int i): call(public Foo.m(int)) <![CDATA[&&]]> args(i); + } </programlisting> - <para>For completeness, a pointcut with a declaration may be declared - <literal>final</literal>. </para> + <para> + For completeness, a pointcut with a declaration may be declared + <literal>final</literal>. + </para> <para> Though named pointcut declarations appear somewhat like method declarations, and can be overridden in subaspects, they cannot be - overloaded. It is an error for two pointcuts to be named with the same - name in the same class or aspect declaration. + overloaded. It is an error for two pointcuts to be named with the + same name in the same class or aspect declaration. </para> <para> - The scope of a named pointcut is the enclosing class declaration. This - is different than the scope of other members; the scope of other - members is the enclosing class <emphasis>body</emphasis>. This means - that the following code is legal: + The scope of a named pointcut is the enclosing class declaration. + This is different than the scope of other members; the scope of + other members is the enclosing class <emphasis>body</emphasis>. + This means that the following code is legal: </para> <programlisting> -aspect B percflow(publicCall()) { - pointcut publicCall(): call(public Foo.m(int)); -} + aspect B percflow(publicCall()) { + pointcut publicCall(): call(public Foo.m(int)); + } </programlisting> - </sect2> <sect2> <title>Context exposure</title> <para> - Pointcuts have an interface; they expose some parts of the execution - context of the join points they pick out. For example, the PublicIntCall - above exposes the first argument from the receptions of all public - unary integer methods. This context is exposed by providing typed - formal parameters to named pointcuts and advice, like the formal - parameters of a Java method. These formal parameters are bound by name - matching. + Pointcuts have an interface; they expose some parts of the + execution context of the join points they pick out. For example, + the PublicIntCall above exposes the first argument from the + receptions of all public unary integer methods. This context is + exposed by providing typed formal parameters to named pointcuts and + advice, like the formal parameters of a Java method. These formal + parameters are bound by name matching. </para> <para> - On the right-hand side of advice or pointcut declarations, in certain - pointcut designators, a Java identifier is allowed in place of a type - or collection of types. The pointcut designators that allow this are - <literal>this</literal>, <literal>target</literal>, and - <literal>args</literal>. In all such cases, using an identifier rather - than a type does two things. First, it selects join points as based on - the type of the formal parameter. So the pointcut + On the right-hand side of advice or pointcut declarations, in + certain pointcut designators, a Java identifier is allowed in place + of a type or collection of types. The pointcut designators that + allow this are <literal>this</literal>, <literal>target</literal>, + and <literal>args</literal>. In all such cases, using an + identifier rather than a type does two things. First, it selects + join points as based on the type of the formal parameter. So the + pointcut </para> <programlisting> -pointcut intArg(int i): args(i); + pointcut intArg(int i): args(i); </programlisting> <para> - picks out join points where an <literal>int</literal> is being passed - as an argument. Second, though, it makes the value of that argument - available to the enclosing advice or pointcut. + picks out join points where an <literal>int</literal> is being + passed as an argument. Second, though, it makes the value of that + argument available to the enclosing advice or pointcut. </para> <para> @@ -578,23 +553,23 @@ pointcut intArg(int i): args(i); </para> <programlisting> -pointcut publicCall(int x): call(public *.*(int)) <![CDATA[&&]]> intArg(x); -pointcut intArg(int i): args(i); + pointcut publicCall(int x): call(public *.*(int)) <![CDATA[&&]]> intArg(x); + pointcut intArg(int i): args(i); </programlisting> <para> - is a legal way to pick out all calls to public methods accepting an int - argument, and exposing that argument. + is a legal way to pick out all calls to public methods accepting an + int argument, and exposing that argument. </para> <para> There is one special case for this kind of exposure. Exposing an - argument of type Object will also match primitive typed arguments, and - expose a "boxed" version of the primitive. So, + argument of type Object will also match primitive typed arguments, + and expose a "boxed" version of the primitive. So, </para> <programlisting> -pointcut publicCall(): call(public *.*(..)) <![CDATA[&&]]> args(Object); + pointcut publicCall(): call(public *.*(..)) <![CDATA[&&]]> args(Object); </programlisting> <para> @@ -604,20 +579,21 @@ pointcut publicCall(): call(public *.*(..)) <![CDATA[&&]]> args(Object); </para> <programlisting> -pointcut publicCall(Object o): call(public *.*(..)) <![CDATA[&&]]> args(o); + pointcut publicCall(Object o): call(public *.*(..)) <![CDATA[&&]]> args(o); </programlisting> <para> - will pick out all unary methods that take any argument: And if the - argument was an <literal>int</literal>, then the value passed to advice - will be of type <literal>java.lang.Integer</literal>. + will pick out all unary methods that take any argument: And if the + argument was an <literal>int</literal>, then the value passed to + advice will be of type <literal>java.lang.Integer</literal>. </para> </sect2> <sect2> <title>Primitive pointcuts</title> - <bridgehead>Method-related pointcuts</bridgehead> + <sect3> + <title>Method-related pointcuts</title> <para>AspectJ provides two primitive pointcut designators designed to capture method call and execution join points. </para> @@ -626,8 +602,10 @@ pointcut publicCall(Object o): call(public *.*(..)) <![CDATA[&&]]> args(o); <listitem><literal>call(<replaceable>MethodPattern</replaceable>)</literal></listitem> <listitem><literal>execution(<replaceable>MethodPattern</replaceable>)</literal></listitem> </itemizedlist> + </sect3> - <bridgehead>Field-related pointcuts</bridgehead> + <sect3> + <title>Field-related pointcuts</title> <para> AspectJ provides two primitive pointcut designators designed to @@ -647,15 +625,19 @@ pointcut publicCall(Object o): call(public *.*(..)) <![CDATA[&&]]> args(o); </para> <programlisting><![CDATA[ -aspect GuardedX { - static final int MAX_CHANGE = 100; - before(int newval): set(int T.x) && args(newval) { - if (Math.abs(newval - T.x) > MAX_CHANGE) - throw new RuntimeException(); - } -}]]></programlisting> + aspect GuardedX { + static final int MAX_CHANGE = 100; + before(int newval): set(int T.x) && args(newval) { + if (Math.abs(newval - T.x) > MAX_CHANGE) + throw new RuntimeException(); + } + } +]]></programlisting> - <bridgehead>Object creation-related pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Object creation-related pointcuts</title> <para> AspectJ provides primitive pointcut designators designed to @@ -663,13 +645,16 @@ aspect GuardedX { </para> <itemizedlist> - <listitem><literal>call(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> - <listitem><literal>execution(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> - <listitem><literal>initialization(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> - <listitem><literal>preinitialization(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> + <listitem><literal>call(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> + <listitem><literal>execution(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> + <listitem><literal>initialization(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> + <listitem><literal>preinitialization(<replaceable>ConstructorPattern</replaceable>)</literal></listitem> </itemizedlist> - <bridgehead>Class initialization-related pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Class initialization-related pointcuts</title> <para> AspectJ provides one primitive pointcut designator to pick out @@ -680,7 +665,10 @@ aspect GuardedX { <listitem><literal>staticinitialization(<replaceable>TypePattern</replaceable>)</literal></listitem> </itemizedlist> - <bridgehead>Exception handler execution-related pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Exception handler execution-related pointcuts</title> <para> AspectJ provides one primitive pointcut designator to capture @@ -700,14 +688,17 @@ aspect GuardedX { </para> <programlisting> -aspect NormalizeFooException { - before(FooException e): handler(FooException) <![CDATA[&&]]> args(e) { - e.normalize(); - } -} + aspect NormalizeFooException { + before(FooException e): handler(FooException) <![CDATA[&&]]> args(e) { + e.normalize(); + } + } </programlisting> - <bridgehead>Advice execution-related pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Advice execution-related pointcuts</title> <para> AspectJ provides one primitive pointcut designator to capture @@ -715,7 +706,7 @@ aspect NormalizeFooException { </para> <itemizedlist> - <listitem><literal>adviceexecution()</literal></listitem> + <listitem><literal>adviceexecution()</literal></listitem> </itemizedlist> <para> @@ -724,16 +715,19 @@ aspect NormalizeFooException { </para> <programlisting> -aspect TraceStuff { - pointcut myAdvice(): adviceexecution() <![CDATA[&&]]> within(TraceStuff); + aspect TraceStuff { + pointcut myAdvice(): adviceexecution() <![CDATA[&&]]> within(TraceStuff); - before(): call(* *(..)) <![CDATA[&&]]> !cflow(myAdvice) { - // do something - } -} + before(): call(* *(..)) <![CDATA[&&]]> !cflow(myAdvice) { + // do something + } + } </programlisting> - <bridgehead>State-based pointcuts</bridgehead> + </sect3> + + <sect3> + <title>State-based pointcuts</title> <para> Many concerns cut across the dynamic times when an object of a @@ -760,7 +754,7 @@ aspect TraceStuff { current join point is transfering control to. This means that the target object is the same as the current object at a method execution join point, for example, but may be different at a method call join - point. + point. </para> <itemizedlist> @@ -782,7 +776,7 @@ aspect TraceStuff { </para> <programlisting> -args(int, .., String) + args(int, .., String) </programlisting> <para> @@ -790,8 +784,10 @@ args(int, .., String) <literal>int</literal> and the last is a <literal>String</literal>. </para> + </sect3> - <bridgehead>Control flow-based pointcuts</bridgehead> + <sect3> + <title>Control flow-based pointcuts</title> <para> Some concerns cut across the control flow of the program. The @@ -824,7 +820,10 @@ args(int, .., String) picked out by <replaceable>Pointcut</replaceable>. </para> - <bridgehead>Program text-based pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Program text-based pointcuts</title> <para> While many concerns cut across the runtime structure of the program, @@ -860,7 +859,10 @@ args(int, .., String) with code in a method or constructor's local or anonymous types. </para> - <bridgehead>Dynamic property-based pointcuts</bridgehead> + </sect3> + + <sect3> + <title>Expression-based pointcuts</title> <itemizedlist> <listitem><literal>if(<replaceable>BooleanExpression</replaceable>)</literal></listitem> @@ -876,9 +878,10 @@ args(int, .., String) </para> <programlisting> -if(thisJoinPoint.getKind().equals("call")) + if(thisJoinPoint.getKind().equals("call")) </programlisting> + </sect3> </sect2> <sect2> @@ -890,77 +893,88 @@ if(thisJoinPoint.getKind().equals("call")) join points. </para> - <bridgehead>Methods</bridgehead> + <sect3> + <title>Methods</title> - <para> - Join points associated with methods typically have method signatures, - consisting of a method name, parameter types, return type, the types of - the declared (checked) exceptions, and some type that the method could - be called on (below called the "qualifying type"). - </para> + <para> + Join points associated with methods typically have method signatures, + consisting of a method name, parameter types, return type, the types of + the declared (checked) exceptions, and some type that the method could + be called on (below called the "qualifying type"). + </para> - <para> - At a method call join point, the signature is a method signature whose - qualifying type is the static type used to <emphasis>access</emphasis> - the method. This means that the signature for the join point created - from the call <literal>((Integer)i).toString()</literal> is different - than that for the call <literal>((Object)i).toString()</literal>, even - if <literal>i</literal> is the same variable. - </para> + <para> + At a method call join point, the signature is a method signature whose + qualifying type is the static type used to <emphasis>access</emphasis> + the method. This means that the signature for the join point created + from the call <literal>((Integer)i).toString()</literal> is different + than that for the call <literal>((Object)i).toString()</literal>, even + if <literal>i</literal> is the same variable. + </para> - <para> - At a method execution join point, the signature a method signature - whose qualifying type is the declaring type of the method. - </para> + <para> + At a method execution join point, the signature a method signature + whose qualifying type is the declaring type of the method. + </para> - <bridgehead>Fields</bridgehead> + </sect3> - <para> - Join points associated with fields typically have field signatures, - consisting of a field name and a field type. A field reference join - point has such a signature, and no parameters. A field set join point - has such a signature, but has a has a single parameter whose type is - the same as the field type. - </para> + <sect3> + <title>Fields</title> - <bridgehead>Constructors</bridgehead> + <para> + Join points associated with fields typically have field signatures, + consisting of a field name and a field type. A field reference join + point has such a signature, and no parameters. A field set join point + has such a signature, but has a has a single parameter whose type is + the same as the field type. + </para> - <para> - Join points associated with constructors typically have constructor - signatures, consisting of a parameter types, the types of the declared - (checked) exceptions, and the declaring type. - </para> + </sect3> - <para> - At a constructor call join point, the signature is the constructor - signature of the called constructor. At a constructor execution join - point, the signature is the constructor signature of the currently - executing constructor. - </para> + <sect3> + <title>Constructors</title> - <para> - At object initialization and pre-initialization join points, the - signature is the constructor signature for the constructor that started - this initialization: the first constructor entered during this type's - initialization of this object. - </para> + <para> + Join points associated with constructors typically have constructor + signatures, consisting of a parameter types, the types of the declared + (checked) exceptions, and the declaring type. + </para> - <bridgehead>Others</bridgehead> + <para> + At a constructor call join point, the signature is the constructor + signature of the called constructor. At a constructor execution join + point, the signature is the constructor signature of the currently + executing constructor. + </para> - <para> - At a handler execution join point, the signature is composed of the - exception type that the handler handles. - </para> + <para> + At object initialization and pre-initialization join points, the + signature is the constructor signature for the constructor that started + this initialization: the first constructor entered during this type's + initialization of this object. + </para> + </sect3> - <para> - At an advice execution join point, the signature is composed of the - aspect type, the parameter types of the advice, the return type (void - for all but around advice) and the types of the declared (checked) - exceptions. - </para> + <sect3> + <title>Others</title> + <para> + At a handler execution join point, the signature is composed of the + exception type that the handler handles. + </para> + + <para> + At an advice execution join point, the signature is composed of the + aspect type, the parameter types of the advice, the return type (void + for all but around advice) and the types of the declared (checked) + exceptions. + </para> + </sect3> </sect2> +<!-- ============================== --> + <sect2> <title>Matching</title> @@ -985,9 +999,9 @@ if(thisJoinPoint.getKind().equals("call")) <programlisting> -class C { - public final void foo() throws ArrayOutOfBoundsException { ... } -} + class C { + public final void foo() throws ArrayOutOfBoundsException { ... } + } </programlisting> <para> @@ -997,7 +1011,7 @@ class C { <programlisting> -call(public final void C.foo() throws ArrayOutOfBoundsException) + call(public final void C.foo() throws ArrayOutOfBoundsException) </programlisting> <para> @@ -1005,7 +1019,7 @@ call(public final void C.foo() throws ArrayOutOfBoundsException) </para> <programlisting> -call(public final void *.*() throws ArrayOutOfBoundsException) + call(public final void *.*() throws ArrayOutOfBoundsException) </programlisting> @@ -1023,7 +1037,7 @@ call(public final void *.*() throws ArrayOutOfBoundsException) </para> <programlisting> -call(public final void *() throws ArrayOutOfBoundsException) + call(public final void *() throws ArrayOutOfBoundsException) </programlisting> <para> @@ -1032,7 +1046,7 @@ call(public final void *() throws ArrayOutOfBoundsException) </para> <programlisting> -execution(void m(..)) + execution(void m(..)) </programlisting> <para> @@ -1041,10 +1055,9 @@ execution(void m(..)) </para> <programlisting> -execution(void m(.., int)) + execution(void m(.., int)) </programlisting> - <para> picks out execution join points for void methods named <literal>m</literal> whose last parameter is of type @@ -1059,7 +1072,7 @@ execution(void m(.., int)) </para> <programlisting> -withincode(!public void foo()) + withincode(!public void foo()) </programlisting> <para> @@ -1068,7 +1081,7 @@ withincode(!public void foo()) </para> <programlisting> -withincode(void foo()) + withincode(void foo()) </programlisting> <para> @@ -1082,7 +1095,7 @@ withincode(void foo()) </para> <programlisting> -call(int *()) + call(int *()) </programlisting> <para> @@ -1091,7 +1104,7 @@ call(int *()) </para> <programlisting> -call(int get*()) + call(int get*()) </programlisting> <para> @@ -1107,8 +1120,93 @@ call(int get*()) </para> <programlisting> -execution(private C.new() throws ArithmeticException) + execution(private C.new() throws ArithmeticException) </programlisting> + + <sect3> + <title>Matching based on the throws clause</title> + + <para> + Type patterns may be used to pick out methods and constructors + based on their throws clauses. This allows the following two + kinds of extremely wildcarded pointcuts: + </para> + +<programlisting> + pointcut throwsMathlike(): + // each call to a method with a throws clause containing at least + // one exception exception with "Math" in its name. + call(* *(..) throws *..*Math*); + + pointcut doesNotThrowMathlike(): + // each call to a method with a throws clause containing no + // exceptions with "Math" in its name. + call(* *(..) throws !*..*Math*); +</programlisting> + + <para> + A <replaceable>ThrowsClausePattern</replaceable> is a comma-separated list of + <replaceable>ThrowsClausePatternItem</replaceable>s, where + + <variablelist> + <varlistentry> + <term><replaceable>ThrowsClausePatternItem</replaceable> :</term> + <listitem> + <literal>[ ! ] + <replaceable>TypeNamePattern</replaceable></literal> + </listitem> + </varlistentry> + </variablelist> + </para> + + <para> + A <replaceable>ThrowsClausePattern</replaceable> matches the + throws clause of any code member signature. To match, each + <literal>ThrowsClausePatternItem</literal> must + match the throws clause of the member in question. If any item + doesn't match, then the whole pattern doesn't match. + </para> + + <para> + If a ThrowsClausePatternItem begins with "!", then it matches a + particular throws clause if and only if <emphasis>none</emphasis> + of the types named in the throws clause is matched by the + <literal>TypeNamePattern</literal>. + </para> + + <para> + If a <replaceable>ThrowsClausePatternItem</replaceable> does not + begin with "!", then it matches a throws clause if and only if + <emphasis>any</emphasis> of the types named in the throws clause + is matched by the <emphasis>TypeNamePattern</emphasis>. + </para> + + <para> + The rule for "!" matching has one potentially surprising + property, in that these two pointcuts + + <itemizedlist> + <listitem> call(* *(..) throws !IOException) </listitem> + <listitem> call(* *(..) throws (!IOException)) </listitem> + </itemizedlist> + + will match differently on calls to + + <blockquote> + <literal> + void m() throws RuntimeException, IOException {} + </literal> + </blockquote> + </para> + + <para> + [1] will NOT match the method m(), because method m's throws + clause declares that it throws IOException. [2] WILL match the + method m(), because method m's throws clause declares the it + throws some exception which does not match IOException, + i.e. RuntimeException. + </para> + </sect3> </sect2> <sect2> @@ -1120,164 +1218,200 @@ execution(private C.new() throws ArithmeticException) using type patterns are simple. </para> - <bridgehead>Type name patterns</bridgehead> + <sect3> + <title>Type name patterns</title> - <para> - First, all type names are also type patterns. So - <literal>Object</literal>, <literal>java.util.HashMap</literal>, - <literal>Map.Entry</literal>, <literal>int</literal> are all type - patterns. - </para> + <para> + First, all type names are also type patterns. So + <literal>Object</literal>, <literal>java.util.HashMap</literal>, + <literal>Map.Entry</literal>, <literal>int</literal> are all type + patterns. + </para> - <para> - There is a special type name, *, which is also a type pattern. * picks out all - types, including primitive types. So - </para> + <para> + There is a special type name, *, which is also a type pattern. * picks out all + types, including primitive types. So + </para> <programlisting> -call(void foo(*)) + call(void foo(*)) </programlisting> - <para> - picks out all call join points to void methods named foo, taking one - argument of any type. - </para> + <para> + picks out all call join points to void methods named foo, taking one + argument of any type. + </para> - <para> - Type names that contain the two wildcards "*" and - "<literal>..</literal>" are also type patterns. The * wildcard matches - zero or more characters characters except for ".", so it can be used - when types have a certain naming convention. So - </para> + <para> + Type names that contain the two wildcards "*" and + "<literal>..</literal>" are also type patterns. The * wildcard matches + zero or more characters characters except for ".", so it can be used + when types have a certain naming convention. So + </para> <programlisting> -handler(java.util.*Map) + handler(java.util.*Map) </programlisting> - <para> - picks out the types java.util.Map and java.util.java.util.HashMap, - among others, and - </para> + <para> + picks out the types java.util.Map and java.util.java.util.HashMap, + among others, and + </para> <programlisting> -handler(java.util.*) + handler(java.util.*) </programlisting> - <para> - picks out all types that start with "<literal>java.util.</literal>" and - don't have any more "."s, that is, the types in the - <literal>java.util</literal> package, but not inner types - (such as java.util.Map.Entry). - </para> + <para> + picks out all types that start with "<literal>java.util.</literal>" and + don't have any more "."s, that is, the types in the + <literal>java.util</literal> package, but not inner types + (such as java.util.Map.Entry). + </para> - <para> - The "<literal>..</literal>" wildcard matches any sequence of - characters that start and end with a ".", so it can be used - to pick out all types in any subpackage, or all inner types. So - </para> + <para> + The "<literal>..</literal>" wildcard matches any sequence of + characters that start and end with a ".", so it can be used + to pick out all types in any subpackage, or all inner types. So + </para> <programlisting> -within(com.xerox..*) + within(com.xerox..*) </programlisting> - <para> - picks out all join points where the code is in any type - definition of a type whose name begins with "<literal>com.xerox.</literal>". - </para> + <para> + picks out all join points where the code is in any type + definition of a type whose name begins with "<literal>com.xerox.</literal>". + </para> - <bridgehead>Subtype patterns</bridgehead> + </sect3> - <para> - It is possible to pick out all subtypes of a type (or a collection of - types) with the "+" wildcard. The "+" wildcard follows immediately a - type name pattern. So, while - </para> + <sect3> + <title>Subtype patterns</title> + + <para> + It is possible to pick out all subtypes of a type (or a collection of + types) with the "+" wildcard. The "+" wildcard follows immediately a + type name pattern. So, while + </para> <programlisting> -call(Foo.new()) + call(Foo.new()) </programlisting> - <para> - picks out all constructor call join points where an instance of exactly - type Foo is constructed, - </para> + <para> + picks out all constructor call join points where an instance of exactly + type Foo is constructed, + </para> <programlisting> -call(Foo+.new()) + call(Foo+.new()) </programlisting> - <para> - picks out all constructor call join points where an instance of any - subtype of Foo (including Foo itself) is constructed, and the unlikely - </para> + <para> + picks out all constructor call join points where an instance of any + subtype of Foo (including Foo itself) is constructed, and the unlikely + </para> <programlisting> -call(*Handler+.new()) + call(*Handler+.new()) </programlisting> - <para> - picks out all constructor call join points where an instance of any - subtype of any type whose name ends in "Handler" is constructed. - </para> + <para> + picks out all constructor call join points where an instance of any + subtype of any type whose name ends in "Handler" is constructed. + </para> - <bridgehead>Array type patterns</bridgehead> + </sect3> - <para> - A type name pattern or subtype pattern can be followed by one or more - sets of square brackets to make array type patterns. So - <literal>Object[]</literal> is an array type pattern, and so is - <literal>com.xerox..*[][]</literal>, and so is - <literal>Object+[]</literal>. - </para> + <sect3> + <title>Array type patterns</title> - <bridgehead>Type patterns</bridgehead> + <para> + A type name pattern or subtype pattern can be followed by one or more + sets of square brackets to make array type patterns. So + <literal>Object[]</literal> is an array type pattern, and so is + <literal>com.xerox..*[][]</literal>, and so is + <literal>Object+[]</literal>. + </para> + </sect3> - <para> - Type patterns are built up out of type name patterns, subtype patterns, - and array type patterns, and constructed with boolean operators - <literal><![CDATA[&&]]></literal>, <literal>||</literal>, and - <literal>!</literal>. So - </para> + <sect3> + <title>Type patterns</title> + + <para> + Type patterns are built up out of type name patterns, subtype patterns, + and array type patterns, and constructed with boolean operators + <literal><![CDATA[&&]]></literal>, <literal>||</literal>, and + <literal>!</literal>. So + </para> <programlisting> -staticinitialization(Foo || Bar) + staticinitialization(Foo || Bar) </programlisting> - <para> - picks out the static initializer execution join points of either Foo or Bar, - and - </para> + <para> + picks out the static initializer execution join points of either Foo or Bar, + and + </para> <programlisting> -call((Foo+ <![CDATA[&&]]> ! Foo).new(..)) + call((Foo+ <![CDATA[&&]]> ! Foo).new(..)) </programlisting> - <para> - picks out the constructor call join points when a subtype of Foo, but - not Foo itself, is constructed. - </para> + <para> + picks out the constructor call join points when a subtype of Foo, but + not Foo itself, is constructed. + </para> + </sect3> </sect2> </sect1> <!-- ============================== --> - <sect1 id="advice"> + <sect1 id="semantics-advice"> <title>Advice</title> - <itemizedlist> - <listitem><literal>before(<replaceable>Formals</replaceable>): <replaceable>Pointcut</replaceable> { <replaceable>Body</replaceable> }</literal></listitem> - <listitem><literal>after(<replaceable>Formals</replaceable>) returning [ (<replaceable>Formal</replaceable>) ]: <replaceable>Pointcut</replaceable> { <replaceable>Body</replaceable> }</literal></listitem> - <listitem><literal>after(<replaceable>Formals</replaceable>) throwing [ (<replaceable>Formal</replaceable>) ]: <replaceable>Pointcut</replaceable> { <replaceable>Body</replaceable> }</literal></listitem> - <listitem><literal>after(<replaceable>Formals</replaceable>) : <replaceable>Pointcut</replaceable> { <replaceable>Body</replaceable> }</literal></listitem> - <listitem><literal><replaceable>Type</replaceable> around(<replaceable>Formals</replaceable>) [ throws <replaceable>TypeList</replaceable> ] : <replaceable>Pointcut</replaceable> { <replaceable>Body</replaceable> }</literal></listitem> - </itemizedlist> + <para> + Each piece of advice is of the form + + <blockquote> + <literal>[ strictfp ] <replaceable>AdviceSpec</replaceable> [ + throws <replaceable>TypeList</replaceable> ] : + <replaceable>Pointcut</replaceable> { + <replaceable>Body</replaceable> } </literal> + </blockquote> + + where <replaceable>AdviceSpec</replaceable> is one of + </para> + + <itemizedlist> + <listitem> + <literal>before( <replaceable>Formals</replaceable> ) </literal> + </listitem> + <listitem> + <literal>after( <replaceable>Formals</replaceable> ) returning + [ ( <replaceable>Formal</replaceable> ) ] </literal> + </listitem> + <listitem> + <literal>after( <replaceable>Formals</replaceable> ) throwing [ + ( <replaceable>Formal</replaceable> ) ] </literal> + </listitem> + <listitem> + <literal>after( <replaceable>Formals</replaceable> ) </literal> + </listitem> + <listitem> + <literal><replaceable>Type</replaceable> + around( <replaceable>Formals</replaceable> )</literal> + </listitem> + </itemizedlist> <para> Advice defines crosscutting behavior. It is defined in terms of - pointcuts. The code of a piece of advice runs at every join point picked - out by its pointcut. Exactly how the code runs depends on the kind of - advice. + pointcuts. The code of a piece of advice runs at every join point + picked out by its pointcut. Exactly how the code runs depends on the + kind of advice. </para> <para> @@ -1296,18 +1430,18 @@ call((Foo+ <![CDATA[&&]]> ! Foo).new(..)) </para> <programlisting> -aspect A { - pointcut publicCall(): call(public Object *(..)); - after() returning (Object o): publicCall() { - System.out.println("Returned normally with " + o); - } - after() throwing (Exception e): publicCall() { - System.out.println("Threw an exception: " + e); - } - after(): publicCall(){ - System.out.println("Returned or threw an Exception"); - } -} + aspect A { + pointcut publicCall(): call(public Object *(..)); + after() returning (Object o): publicCall() { + System.out.println("Returned normally with " + o); + } + after() throwing (Exception e): publicCall() { + System.out.println("Threw an exception: " + e); + } + after(): publicCall(){ + System.out.println("Returned or threw an Exception"); + } + } </programlisting> <para> @@ -1316,9 +1450,9 @@ aspect A { </para> <programlisting> -after() returning: call(public Object *(..)) { - System.out.println("Returned normally"); -} + after() returning: call(public Object *(..)) { + System.out.println("Returned normally"); + } </programlisting> <para> @@ -1327,9 +1461,9 @@ after() returning: call(public Object *(..)) { </para> <programlisting> -after() returning (byte b): call(int String.length()) { - // this is an error -} + after() returning (byte b): call(int String.length()) { + // this is an error + } </programlisting> <para> @@ -1359,11 +1493,11 @@ after() returning (byte b): call(int String.length()) { </para> <programlisting> -aspect A { - int around(): call(int C.foo()) { - return 3; - } -} + aspect A { + int around(): call(int C.foo()) { + return 3; + } + } </programlisting> <para> @@ -1372,7 +1506,7 @@ aspect A { </para> <programlisting> -proceed( ... ) + proceed( ... ) </programlisting> <para> @@ -1384,12 +1518,12 @@ proceed( ... ) <programlisting> -aspect A { - int around(int i): call(int C.foo(Object, int)) <![CDATA[&&]]> args(i) { - int newi = proceed(i*2) - return newi/2; - } -} + aspect A { + int around(int i): call(int C.foo(Object, int)) <![CDATA[&&]]> args(i) { + int newi = proceed(i*2) + return newi/2; + } + } </programlisting> <para> @@ -1402,12 +1536,12 @@ aspect A { </para> <programlisting> -aspect A { - Object around(int i): call(int C.foo(Object, int)) <![CDATA[&&]]> args(i) { - Integer newi = (Integer) proceed(i*2) - return new Integer(newi.intValue() / 2); - } -} + aspect A { + Object around(int i): call(int C.foo(Object, int)) <![CDATA[&&]]> args(i) { + Integer newi = (Integer) proceed(i*2) + return new Integer(newi.intValue() / 2); + } + } </programlisting> <para> @@ -1418,11 +1552,11 @@ aspect A { </para> <programlisting> -aspect A { - after() returning (int i): call(int C.foo()) { - i = i * 2; - } -} + aspect A { + after() returning (int i): call(int C.foo()) { + i = i * 2; + } + } </programlisting> <para> @@ -1457,22 +1591,22 @@ aspect A { </para> <programlisting> -import java.io.FileNotFoundException; - -class C { - int i; - - int getI() { return i; } -} - -aspect A { - before(): get(int C.i) { - throw new FileNotFoundException(); - } - before() throws FileNotFoundException: get(int C.i) { - throw new FileNotFoundException(); - } -} + import java.io.FileNotFoundException; + + class C { + int i; + + int getI() { return i; } + } + + aspect A { + before(): get(int C.i) { + throw new FileNotFoundException(); + } + before() throws FileNotFoundException: get(int C.i) { + throw new FileNotFoundException(); + } + } </programlisting> <para> @@ -1488,52 +1622,52 @@ aspect A { <varlistentry> <term>method call and execution</term> <listitem> - <para>the checked exceptions declared by the target method's - <literal>throws</literal> clause.</para> + the checked exceptions declared by the target method's + <literal>throws</literal> clause. </listitem> </varlistentry> <varlistentry> <term>constructor call and execution</term> <listitem> - <para>the checked exceptions declared by the target constructor's - <literal>throws</literal> clause.</para> + the checked exceptions declared by the target constructor's + <literal>throws</literal> clause. </listitem> </varlistentry> <varlistentry> <term>field get and set</term> <listitem> - <para>no checked exceptions can be thrown from these join points. </para> + no checked exceptions can be thrown from these join points. </listitem> </varlistentry> <varlistentry> <term>exception handler execution</term> <listitem> - <para>the exceptions that can be thrown by the target exception handler.</para> + the exceptions that can be thrown by the target exception handler. </listitem> </varlistentry> <varlistentry> <term>static initializer execution</term> <listitem> - <para>no checked exceptions can be thrown from these join points. </para> + no checked exceptions can be thrown from these join points. </listitem> </varlistentry> <varlistentry> - <term>pre-initialization, and initialization</term> + <term>pre-initialization and initialization</term> <listitem> - <para>any exception that is in the throws clause of - <emphasis>all</emphasis> constructors of the initialized class. </para> + any exception that is in the throws clause of + <emphasis>all</emphasis> constructors of the initialized class. </listitem> </varlistentry> <varlistentry> <term>advice execution</term> <listitem> - <para>any exception that is in the throws clause of the advice. </para> + any exception that is in the throws clause of the advice. </listitem> </varlistentry> @@ -1569,7 +1703,7 @@ aspect A { <listitem> Otherwise, if aspect A is a subaspect of aspect B, then all advice defined in A has precedence over all advice defined in - B. So, unless otherwise specified with + B. So, unless otherwise specified with <literal>declare precedence</literal>, advice in a subaspect has precedence over advice in a superaspect. </listitem> @@ -1598,15 +1732,14 @@ aspect A { <para>These rules can lead to circularity, such as</para> <programlisting> -aspect A { - before(): execution(void main(String[] args)) {} - after(): execution(void main(String[] args)) {} - before(): execution(void main(String[] args)) {} -} + aspect A { + before(): execution(void main(String[] args)) {} + after(): execution(void main(String[] args)) {} + before(): execution(void main(String[] args)) {} + } </programlisting> <para>such circularities will result in errors signalled by the compiler. </para> - </sect3> <sect3> @@ -1642,7 +1775,6 @@ aspect A { there is no further advice. Then the body of the advice will run. </para> </sect3> - </sect2> <sect2> @@ -1661,7 +1793,7 @@ aspect A { <programlisting> -pointcut publicCall(): call(public * *(..)); + pointcut publicCall(): call(public * *(..)); </programlisting> @@ -1705,7 +1837,7 @@ pointcut publicCall(): call(public * *(..)); </sect1> - <sect1 id="staticCrosscutting"> + <sect1 id="semantics-declare"> <title>Static crosscutting</title> <para> @@ -1715,14 +1847,13 @@ pointcut publicCall(): call(public * *(..)); inter-type member declarations and other <literal>declare</literal> forms. </para> - <sect2> <title>Inter-type member declarations</title> - <para> - AspectJ allows the declaration of members by aspects that are - associated with other types. - </para> + <para> + AspectJ allows the declaration of members by aspects that are + associated with other types. + </para> <para> An inter-type method declaration looks like @@ -1730,18 +1861,18 @@ pointcut publicCall(): call(public * *(..)); <itemizedlist> <listitem><literal> - [ <replaceable>Modifiers</replaceable> ] + [ <replaceable>Modifiers</replaceable> ] <replaceable>Type</replaceable> <replaceable>OnType</replaceable> . - <replaceable>Id</replaceable>(<replaceable>Formals</replaceable>) - [ <replaceable>ThrowsClause</replaceable> ] + <replaceable>Id</replaceable>(<replaceable>Formals</replaceable>) + [ <replaceable>ThrowsClause</replaceable> ] { <replaceable>Body</replaceable> }</literal></listitem> - <listitem><literal>abstract - [ <replaceable>Modifiers</replaceable> ] + <listitem><literal>abstract + [ <replaceable>Modifiers</replaceable> ] <replaceable>Type</replaceable> <replaceable>OnType</replaceable> . <replaceable>Id</replaceable>(<replaceable>Formals</replaceable>) - [ <replaceable>ThrowsClause</replaceable> ] + [ <replaceable>ThrowsClause</replaceable> ] ; </literal></listitem> </itemizedlist> @@ -1754,17 +1885,17 @@ pointcut publicCall(): call(public * *(..)); </para> <programlisting> -interface Iface {} - -aspect A { - private void Iface.m() { - System.err.println("I'm a private method on an interface"); - } - void worksOnI(Iface iface) { - // calling a private method on an interface - iface.m(); - } -} + interface Iface {} + + aspect A { + private void Iface.m() { + System.err.println("I'm a private method on an interface"); + } + void worksOnI(Iface iface) { + // calling a private method on an interface + iface.m(); + } + } </programlisting> <para> @@ -1773,10 +1904,10 @@ aspect A { <itemizedlist> <listitem><literal> - [ <replaceable>Modifiers</replaceable> ] - <replaceable>OnType</replaceable> . new ( - <replaceable>Formals</replaceable> ) - [ <replaceable>ThrowsClause</replaceable> ] + [ <replaceable>Modifiers</replaceable> ] + <replaceable>OnType</replaceable> . new ( + <replaceable>Formals</replaceable> ) + [ <replaceable>ThrowsClause</replaceable> ] { <replaceable>Body</replaceable> }</literal></listitem> </itemizedlist> @@ -1787,20 +1918,29 @@ aspect A { </para> <para> + Note that in the Java language, classes that define no constructors + have an implicit no-argument constructor that just calls + <literal>super()</literal>. This means that attempting to declare + a no-argument inter-type constructor on such a class may result in + a conflict, even though it <emphasis>looks</emphasis> like no + constructor is defined. + </para> + + <para> An inter-type field declaration looks like one of </para> <itemizedlist> <listitem><literal> - [ <replaceable>Modifiers</replaceable> ] - <replaceable>Type</replaceable> - <replaceable>OnType</replaceable> . <replaceable>Id</replaceable> - = <replaceable>Expression</replaceable>;</literal></listitem> + [ <replaceable>Modifiers</replaceable> ] + <replaceable>Type</replaceable> + <replaceable>OnType</replaceable> . <replaceable>Id</replaceable> + = <replaceable>Expression</replaceable>;</literal></listitem> <listitem><literal> - [ <replaceable>Modifiers</replaceable> ] - <replaceable>Type</replaceable> - <replaceable>OnType</replaceable> . <replaceable>Id</replaceable>;</literal></listitem> + [ <replaceable>Modifiers</replaceable> ] + <replaceable>Type</replaceable> + <replaceable>OnType</replaceable> . <replaceable>Id</replaceable>;</literal></listitem> </itemizedlist> <para> @@ -1809,6 +1949,12 @@ aspect A { <replaceable>OnType</replaceable> is an interface. Even if the field is neither public, nor static, nor final. </para> + + <para> + The initializer, if any, of an inter-type field definition runs + before the class-local initializers defined in its target class. + </para> + </sect2> <para> @@ -1843,12 +1989,12 @@ aspect A { supports) is very different from inserting a private method declaration into another class. The former allows access only from the declaring aspect, while the latter would allow access only from the target type. - Java serialization, for example, uses the presense of a private method - <literal>void writeObject(ObjectOutputStream)</literal> for the - implementation of <literal>java.io.Serializable</literal>. A private - inter-type declaration of that method would not fulfill this - requirement, since it would be private to the aspect, not private to - the target type. + Java serialization, for example, uses the presense of a private method + <literal>void writeObject(ObjectOutputStream)</literal> for the + implementation of <literal>java.io.Serializable</literal>. A private + inter-type declaration of that method would not fulfill this + requirement, since it would be private to the aspect, not private to + the target type. </para> </sect2> @@ -1863,13 +2009,13 @@ aspect A { </para> <programlisting> -aspect A { - private Registry otherPackage.*.r; - public void otherPackage.*.register(Registry r) { - r.register(this); - this.r = r; - } -} + aspect A { + private Registry otherPackage.*.r; + public void otherPackage.*.register(Registry r) { + r.register(this); + this.r = r; + } + } </programlisting> <para> @@ -1895,7 +2041,7 @@ aspect A { </para> <programlisting> -this.r = r + this.r = r </programlisting> <para> @@ -1944,12 +2090,12 @@ this.r = r <para> An aspect may change the inheritance hierarchy of a system by changing - the a superclass of a type or adding a superinterface onto a type, with + the superclass of a type or adding a superinterface onto a type, with the <literal>declare parents</literal> form. </para> <itemizedlist> - <listitem><literal>declare parents: <replaceable>TypePattern</replaceable> extends <replaceable>TypeList</replaceable>;</literal></listitem> + <listitem><literal>declare parents: <replaceable>TypePattern</replaceable> extends <replaceable>Type</replaceable>;</literal></listitem> <listitem><literal>declare parents: <replaceable>TypePattern</replaceable> implements <replaceable>TypeList</replaceable>;</literal></listitem> </itemizedlist> @@ -1963,10 +2109,10 @@ this.r = r </para> <programlisting> -aspect A { - declare parents: SomeClass implements Runnable; - public void SomeClass.run() { ... } -} + aspect A { + declare parents: SomeClass implements Runnable; + public void SomeClass.run() { ... } + } </programlisting> </sect2> @@ -1996,13 +2142,13 @@ aspect A { </para> <programlisting> - Object M O - \ / \ / - C N Q - \ / / - D P - \ / - E + Object M O + \ / \ / + C N Q + \ / / + D P + \ / + E </programlisting> <para> @@ -2010,7 +2156,7 @@ aspect A { </para> <programlisting> - Object M C O N D Q P E + Object M C O N D Q P E </programlisting> </sect2> @@ -2052,9 +2198,9 @@ aspect A { <para>For example, the aspect</para> <programlisting> -aspect A { - declare soft: Exception: execution(void main(String[] args)); -} + aspect A { + declare soft: Exception: execution(void main(String[] args)); + } </programlisting> <para>Would, at the execution join point, catch any @@ -2065,14 +2211,14 @@ aspect A { <para>This is similar to what the following advice would do</para> <programlisting> -aspect A { - void around() execution(void main(String[] args)) { - try { proceed(); } - catch (Exception e) { - throw new org.aspectj.lang.SoftException(e); - } - } -} + aspect A { + void around() execution(void main(String[] args)) { + try { proceed(); } + catch (Exception e) { + throw new org.aspectj.lang.SoftException(e); + } + } + } </programlisting> <para>except, in addition to wrapping the exception, it also affects @@ -2089,56 +2235,148 @@ aspect A { </para> <itemizedlist> - <listitem><literal>declare precedence : <replaceable>TypePatternList</replaceable></literal></listitem> + <listitem><literal>declare precedence : + <replaceable>TypePatternList</replaceable> ; </literal></listitem> </itemizedlist> - <para>This signifies that if any join point has advice from two concrete - aspects matched by some pattern in - <replaceable>TypePatternList</replaceable>, then the precence of the - advice will be the order of in the list. </para> + <para>This signifies that if any join point has advice from two + concrete aspects matched by some pattern in + <replaceable>TypePatternList</replaceable>, then the precedence of + the advice will be the order of in the list. </para> <para>In <replaceable>TypePatternList</replaceable>, the wildcard "*" can appear at most once, and it means "any type not matched by any other pattern in the list". </para> - <para>For example, the constraints that (1) aspects that have Security as - part of their name should have precedence over all other aspects, and (2) - the Logging aspect (and any aspect that extends it) should have - precedence over all non-security aspects, can be expressed by:</para> + <para>For example, the constraints that (1) aspects that have + Security as part of their name should have precedence over all other + aspects, and (2) the Logging aspect (and any aspect that extends it) + should have precedence over all non-security aspects, can be + expressed by:</para> <programlisting> - declare precedence: *..*Security*, Logging+, *; + declare precedence: *..*Security*, Logging+, *; </programlisting> <para> For another example, the CountEntry aspect might want to count the - entry to methods in the current package accepting a Type object as its - first argument. However, it should count all entries, even those that - the aspect DisallowNulls causes to throw exceptions. This can be - accomplished by stating that CountEntry has precedence over - DisallowNulls. This declaration could be in either aspect, or in - another, ordering aspect: + entry to methods in the current package accepting a Type object as + its first argument. However, it should count all entries, even + those that the aspect DisallowNulls causes to throw exceptions. + This can be accomplished by stating that CountEntry has precedence + over DisallowNulls. This declaration could be in either aspect, or + in another, ordering aspect: </para> +<programlisting> + aspect Ordering { + declare precedence: CountEntry, DisallowNulls; + } + aspect DisallowNulls { + pointcut allTypeMethods(Type obj): call(* *(..)) <![CDATA[&&]]> args(obj, ..); + before(Type obj): allTypeMethods(obj) { + if (obj == null) throw new RuntimeException(); + } + } + aspect CountEntry { + pointcut allTypeMethods(Type obj): call(* *(..)) <![CDATA[&&]]> args(obj, ..); + static int count = 0; + before(): allTypeMethods(Type) { + count++; + } + } +</programlisting> + + <sect3> + <title>Various cycles</title> + + <para> + It is an error for any aspect to be matched by more than one + TypePattern in a single decare precedence, so: + </para> + +<programlisting> + declare precedence: A, B, A ; // error +</programlisting> + + <para> + However, multiple declare precedence forms may legally have this + kind of circularity. For example, each of these declare + precedence is perfectly legal: + </para> + +<programlisting> + declare precedence: B, A; + declare precedence: A, B; +</programlisting> + + <para> + And a system in which both constraints are active may also be + legal, so long as advice from A and B don't share a join + point. So this is an idiom that can be used to enforce that A and + B are strongly independent. + </para> + </sect3> + + <sect3> + <title>Applies to concrete aspects</title> + + <para> + Consider the following library aspects: + </para> + +<programlisting> + abstract aspect Logging { + abstract pointcut logged(); + + before(): logged() { + System.err.println("thisJoinPoint: " + thisJoinPoint); + } + } + + aspect aspect MyProfiling { + abstract pointcut profiled(); + + Object around(): profiled() { + long beforeTime = System.currentTimeMillis(); + try { + return proceed(); + } finally { + long afterTime = System.currentTimeMillis(); + addToProfile(thisJoinPointStaticPart, + afterTime - beforeTime); + } + } + abstract void addToProfile( + org.aspectj.JoinPoint.StaticPart jp, + long elapsed); + } +</programlisting> + + <para> + In order to use either aspect, they must be extended with + concrete aspects, say, MyLogging and MyProfiling. Because advice + only applies from concrete aspects, the declare precedence form + only matters when declaring precedence with concrete aspects. So + </para> <programlisting> -aspect Ordering { - declare precedence: CountEntry, DisallowNulls; -} -aspect DisallowNulls { - pointcut allTypeMethods(Type obj): call(* *(..)) <![CDATA[&&]]> args(obj, ..); - before(Type obj): allTypeMethods(obj) { - if (obj == null) throw new RuntimeException(); - } -} -aspect CountEntry { - pointcut allTypeMethods(Type obj): call(* *(..)) <![CDATA[&&]]> args(obj, ..); - static int count = 0; - before(): allTypeMethods(Type) { - count++; - } -} + declare precedence: Logging, Profiling; </programlisting> + + <para> + has no effect, but both + </para> + +<programlisting> + declare precedence: MyLogging, MyProfiling; + declare precedence: Logging+, Profiling+; +</programlisting> + + <para> + are meaningful. + </para> + </sect3> </sect2> @@ -2167,7 +2405,7 @@ aspect CountEntry { </sect2> </sect1> - <sect1 id="aspects"> + <sect1 id="semantics-aspects"> <title>Aspects</title> <para> @@ -2348,6 +2586,50 @@ aspect CountEntry { control flow. </para> </sect3> + + <sect3> + <title>Aspect instantiation and advice</title> + + <para> + All advice runs in the context of an aspect instance, + but it is possible to write a piece of advice with a pointcut + that picks out a join point that must occur before asopect + instantiation. For example: + </para> + +<programlisting> + public class Client + { + public static void main(String[] args) { + Client c = new Client(); + } + } + + aspect Watchcall { + pointcut myConstructor(): execution(new(..)); + + before(): myConstructor() { + System.err.println("Entering Constructor"); + } + } +</programlisting> + + <para> + The before advice should run before the execution of all + constructors in the system. It must run in the context of an + instance of the Watchcall aspect. The only way to get such an + instance is to have Watchcall's default constructor execute. But + before that executes, we need to run the before advice... + </para> + + <para> + There is no general way to detect these kinds of circularities at + compile time. If advice runs before its aspect is instantiated, + AspectJ will throw a <ulink + url="../api/org/aspectj/lang/NoAspectBoundException.html"> + <literal>org.aspectj.lang.NoAspectBoundException</literal></ulink>. + </para> + </sect3> </sect2> <sect2> @@ -2373,18 +2655,17 @@ aspect CountEntry { access to all members, even private ones. </para> - <programlisting> -class C { - private int i = 0; - void incI(int x) { i = i+x; } -} -privileged aspect A { - static final int MAX = 1000; - before(int x, C c): call(void C.incI(int)) <![CDATA[&&]]> target(c) <![CDATA[&&]]> args(x) { - if (c.i+x > MAX) throw new RuntimeException(); - } -} + class C { + private int i = 0; + void incI(int x) { i = i+x; } + } + privileged aspect A { + static final int MAX = 1000; + before(int x, C c): call(void C.incI(int)) <![CDATA[&&]]> target(c) <![CDATA[&&]]> args(x) { + if (c.i+x > MAX) throw new RuntimeException(); + } + } </programlisting> <para> @@ -2399,16 +2680,16 @@ privileged aspect A { </para> <programlisting> -class C { - private int i = 0; - void foo() { } -} -privileged aspect A { - private int C.i = 999; - before(C c): call(void C.foo()) target(c) { - System.out.println(c.i); - } -} + class C { + private int i = 0; + void foo() { } + } + privileged aspect A { + private int C.i = 999; + before(C c): call(void C.foo()) target(c) { + System.out.println(c.i); + } + } </programlisting> <para> @@ -2418,17 +2699,11 @@ privileged aspect A { fields even if it were not privileged. </para> + <para> + Note that a privileged aspect can access private inter-type + declarations made by other aspects, since they are simply + considered private members of that other aspect. + </para> </sect2> - - </sect1> - + </sect1> </appendix> - -<!-- -Local variables: -compile-command: "java sax.SAXCount -v progguide.xml && java com.icl.saxon.StyleSheet -w0 progguide.xml progguide.html.xsl" -fill-column: 79 -sgml-local-ecat-files: progguide.ced -sgml-parent-document:("progguide.sgml" "book" "appendix") -End: ---> diff --git a/docs/quick.doc b/docs/quick.doc Binary files differindex 4ad371a0e..5dac4fb7c 100644 --- a/docs/quick.doc +++ b/docs/quick.doc |