You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

semantics.adoc 73KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. [[semantics]]
  2. = Language Semantics
  3. [[semantics-intro]]
  4. == Introduction
  5. AspectJ extends Java by overlaying a concept of join points onto the
  6. existing Java semantics and adding a few new program elements to Java:
  7. A join point is a well-defined point in the execution of a program.
  8. These include method and constructor calls, field accesses and others
  9. described below.
  10. A pointcut picks out join points, and exposes some of the values in the
  11. execution context of those join points. There are several primitive
  12. pointcut designators, and others can be named and defined by the
  13. `pointcut` declaration.
  14. A piece of advice is code that executes at each join point in a
  15. pointcut. Advice has access to the values exposed by the pointcut.
  16. Advice is defined by `before`, `after`, and `around` declarations.
  17. Inter-type declarations form AspectJ's static crosscutting features,
  18. that is, is code that may change the type structure of a program, by
  19. adding to or extending interfaces and classes with new fields,
  20. constructors, or methods. Some inter-type declarations are defined
  21. through an extension of usual method, field, and constructor
  22. declarations, and other declarations are made with a new `declare`
  23. keyword.
  24. An aspect is a crosscutting type that encapsulates pointcuts, advice,
  25. and static crosscutting features. By type, we mean Java's notion: a
  26. modular unit of code, with a well-defined interface, about which it is
  27. possible to do reasoning at compile time. Aspects are defined by the
  28. `aspect` declaration.
  29. [[semantics-joinPoints]]
  30. == Join Points
  31. While aspects define types that crosscut, the AspectJ system does not
  32. allow completely arbitrary crosscutting. Rather, aspects define types
  33. that cut across principled points in a program's execution. These
  34. principled points are called join points.
  35. A join point is a well-defined point in the execution of a program. The
  36. join points defined by AspectJ are:
  37. Method call::
  38. When a method is called, not including super calls of non-static
  39. methods.
  40. Method execution::
  41. When the body of code for an actual method executes.
  42. Constructor call::
  43. When an object is built and that object's initial constructor is
  44. called (i.e., not for `super` or `this` constructor calls). The object
  45. being constructed is returned at a constructor call join point, so its
  46. return type is considered to be the type of the object, and the object
  47. itself may be accessed with `after returning` advice.
  48. Constructor execution::
  49. When the body of code for an actual constructor executes, after its
  50. this or super constructor call. The object being constructed is the
  51. currently executing object, and so may be accessed with the `this()` pointcut.
  52. The constructor execution join point for a constructor that
  53. calls a super constructor also includes any non-static initializers of
  54. enclosing class. No value is returned from a constructor execution
  55. join point, so its return type is considered to be `void`.
  56. Static initializer execution::
  57. When the static initializer for a class executes. No value is returned
  58. from a static initializer execution join point, so its return type is
  59. considered to be `void`.
  60. Object pre-initialization::
  61. Before the object initialization code for a particular class runs.
  62. This encompasses the time between the start of its first called
  63. constructor and the start of its parent's constructor. Thus, the
  64. execution of these join points encompass the join points of the
  65. evaluation of the arguments of `this()` and `super()` constructor calls.
  66. No value is returned from an object pre-initialization join point, so its
  67. return type is considered to be `void`.
  68. Object initialization::
  69. When the object initialization code for a particular class runs. This
  70. encompasses the time between the return of its parent's constructor
  71. and the return of its first called constructor. It includes all the
  72. dynamic initializers and constructors used to create the object. The
  73. object being constructed is the currently executing object, and so may
  74. be accessed with the `this()` pointcut. No value is returned from a constructor
  75. execution join point, so its return type is considered to be `void`.
  76. Field reference::
  77. When a non-constant field is referenced. [Note that references to
  78. constant fields (static final fields bound to a constant string object
  79. or primitive value) are not join points, since Java requires them to
  80. be inlined.]
  81. Field set::
  82. When a field is assigned to. Field set join points are considered to
  83. have one argument, the value the field is being set to. No value is
  84. returned from a field set join point, so its return type is considered
  85. to be void. [Note that the initializations of constant fields (`static final`
  86. fields where the initializer is a constant string object or
  87. primitive value) are not join points, since Java requires their
  88. references to be inlined.]
  89. Handler execution::
  90. When an exception handler executes. Handler execution join points are
  91. considered to have one argument, the exception being handled. No value
  92. is returned from a field set join point, so its return type is
  93. considered to be void.
  94. Advice execution::
  95. When the body of code for a piece of advice executes.
  96. Each join point potentially has three pieces of state associated with
  97. it: the currently executing object, the target object, and an object
  98. array of arguments. These are exposed by the three state-exposing
  99. pointcuts, `this`, `target`, and `args`, respectively.
  100. Informally, the currently executing object is the object that a `this`
  101. expression would pick out at the join point. The target object is where
  102. control or attention is transferred to by the join point. The arguments
  103. are those values passed for that transfer of control or attention.
  104. [cols=",,,",options="header",]
  105. |===
  106. |*Join Point* |*Current Object* |*Target Object* |*Arguments*
  107. |Method Call |executing object* |target object** |method arguments
  108. |Method Execution |executing object* |executing object* |method
  109. arguments
  110. |Constructor Call |executing object* |None |constructor arguments
  111. |Constructor Execution |executing object |executing object |constructor
  112. arguments
  113. |Static initializer execution |None |None |None
  114. |Object pre-initialization |None |None |constructor arguments
  115. |Object initialization |executing object |executing object |constructor
  116. arguments
  117. |Field reference |executing object* |target object** |None
  118. |Field assignment |executing object* |target object** |assigned value
  119. |Handler execution |executing object* |executing object* |caught
  120. exception
  121. |Advice execution |executing aspect |executing aspect |advice arguments
  122. |===
  123. +++*+++ There is no executing object in static contexts such as static method
  124. bodies or static initializers.
  125. +++**+++ There is no target object for join points associated with static
  126. methods or fields.
  127. [[semantics-pointcuts]]
  128. == Pointcuts
  129. A pointcut is a program element that picks out join points and exposes
  130. data from the execution context of those join points. Pointcuts are used
  131. primarily by advice. They can be composed with boolean operators to
  132. build up other pointcuts. The primitive pointcuts and combinators
  133. provided by the language are:
  134. `call(MethodPattern)`::
  135. Picks out each method call join point whose signature matches `_MethodPattern_`.
  136. `execution(MethodPattern)`::
  137. Picks out each method execution join point whose signature matches `_MethodPattern_`.
  138. `get(FieldPattern)`::
  139. Picks out each field reference join point whose signature matches `_FieldPattern_`. [Note that references to constant fields (static final fields bound
  140. to a constant string object or primitive value) are not join points,
  141. since Java requires them to be inlined.]
  142. `set(FieldPattern)`::
  143. Picks out each field set join point whose signature matches `_FieldPattern_`. [Note that the initializations of constant fields (static final
  144. fields where the initializer is a constant string object or primitive
  145. value) are not join points, since Java requires their references to be
  146. inlined.]
  147. `call(ConstructorPattern)`::
  148. Picks out each constructor call join point whose signature matches `_ConstructorPattern_`.
  149. `execution(ConstructorPattern)`::
  150. Picks out each constructor execution join point whose signature
  151. matches `_ConstructorPattern_`.
  152. `initialization(ConstructorPattern)`::
  153. Picks out each object initialization join point whose signature
  154. matches `_ConstructorPattern_`.
  155. `preinitialization(ConstructorPattern)`::
  156. Picks out each object pre-initialization join point whose signature
  157. matches `_ConstructorPattern_`.
  158. `staticinitialization(TypePattern)`::
  159. Picks out each static initializer execution join point whose signature
  160. matches `_TypePattern_`.
  161. `handler(TypePattern)`::
  162. Picks out each exception handler join point whose signature matches `_TypePattern_`.
  163. `adviceexecution()`::
  164. Picks out all advice execution join points.
  165. `within(TypePattern)`::
  166. Picks out each join point where the executing code is defined in a
  167. type matched by `_TypePattern_`.
  168. `withincode(MethodPattern)`::
  169. Picks out each join point where the executing code is defined in a
  170. method whose signature matches `_MethodPattern_`.
  171. `withincode(ConstructorPattern)`::
  172. Picks out each join point where the executing code is defined in a
  173. constructor whose signature matches `_ConstructorPattern_`.
  174. `cflow(Pointcut)`::
  175. Picks out each join point in the control flow of any join point `_P_` picked out by `_Pointcut_` , including `_P_` itself.
  176. `cflowbelow(Pointcut)`::
  177. Picks out each join point in the control flow of any join point `_P_` picked out by `_Pointcut_`, but not `_P_` itself.
  178. `this(Type or Id)`::
  179. Picks out each join point where the currently executing object (the
  180. object bound to `_this_`) is an instance of `_Type_` , or of the type of the identifier `_Id_` (which must be bound in the enclosing advice or pointcut definition).
  181. Will not match any join points from static contexts.
  182. `target(Type or Id)`::
  183. Picks out each join point where the target object (the object on which
  184. a call or field operation is applied to) is an instance of `_Type_` , or of the type of the identifier `_Id_` (which must be bound in the enclosing advice or pointcut definition).
  185. Will not match any calls, gets, or sets of static members.
  186. `args(Type or Id, ...)`::
  187. Picks out each join point where the arguments are instances of the
  188. appropriate type (or type of the identifier if using that form). A `_null_` argument is matched iff the static type of the argument (declared
  189. parameter type or field type) is the same as, or a subtype of, the
  190. specified args type.
  191. `PointcutId(TypePattern or Id, ...)`::
  192. Picks out each join point that is picked out by the user-defined
  193. pointcut designator named by `_PointcutId_` .
  194. `if(BooleanExpression)`::
  195. Picks out each join point where the boolean expression evaluates to `_true_` . The boolean expression used can only access static members,
  196. parameters exposed by the enclosing pointcut or advice, and `_thisJoinPoint_` forms. In particular, it cannot call non-static methods on the aspect
  197. or use return values or exceptions exposed by after advice.
  198. `! Pointcut`::
  199. Picks out each join point that is not picked out by `_Pointcut_` .
  200. `Pointcut0 && Pointcut1`::
  201. Picks out each join points that is picked out by both `_Pointcut0_` and `_Pointcut1_` .
  202. `Pointcut0 || Pointcut1`::
  203. Picks out each join point that is picked out by either pointcuts. `_Pointcut0_` or `_Pointcut1_` .
  204. `( Pointcut )`::
  205. Picks out each join points picked out by `_Pointcut_` .
  206. === Pointcut definition
  207. Pointcuts are defined and named by the programmer with the `pointcut`
  208. declaration.
  209. [source, java]
  210. ....
  211. pointcut publicIntCall(int i):
  212. call(public * *(int)) && args(i);
  213. ....
  214. A named pointcut may be defined in either a class or aspect, and is
  215. treated as a member of the class or aspect where it is found. As a
  216. member, it may have an access modifier such as `public` or `private`.
  217. [source, java]
  218. ....
  219. class C {
  220. pointcut publicCall(int i):
  221. call(public * *(int)) && args(i);
  222. }
  223. class D {
  224. pointcut myPublicCall(int i):
  225. C.publicCall(i) && within(SomeType);
  226. }
  227. ....
  228. Pointcuts that are not final may be declared abstract, and defined
  229. without a body. Abstract pointcuts may only be declared within abstract
  230. aspects.
  231. [source, java]
  232. ....
  233. abstract aspect A {
  234. abstract pointcut publicCall(int i);
  235. }
  236. ....
  237. In such a case, an extending aspect may override the abstract pointcut.
  238. [source, java]
  239. ....
  240. aspect B extends A {
  241. pointcut publicCall(int i): call(public Foo.m(int)) && args(i);
  242. }
  243. ....
  244. For completeness, a pointcut with a declaration may be declared `final`.
  245. Though named pointcut declarations appear somewhat like method
  246. declarations, and can be overridden in subaspects, they cannot be
  247. overloaded. It is an error for two pointcuts to be named with the same
  248. name in the same class or aspect declaration.
  249. The scope of a named pointcut is the enclosing class declaration. This
  250. is different than the scope of other members; the scope of other members
  251. is the enclosing class _body_. This means that the following code is
  252. legal:
  253. [source, java]
  254. ....
  255. aspect B percflow(publicCall()) {
  256. pointcut publicCall(): call(public Foo.m(int));
  257. }
  258. ....
  259. === Context exposure
  260. Pointcuts have an interface; they expose some parts of the execution
  261. context of the join points they pick out. For example, the PublicIntCall
  262. above exposes the first argument from the receptions of all public unary
  263. integer methods. This context is exposed by providing typed formal
  264. parameters to named pointcuts and advice, like the formal parameters of
  265. a Java method. These formal parameters are bound by name matching.
  266. On the right-hand side of advice or pointcut declarations, in certain
  267. pointcut designators, a Java identifier is allowed in place of a type or
  268. collection of types. The pointcut designators that allow this are
  269. `this`, `target`, and `args`. In all such cases, using an identifier
  270. rather than a type does two things. First, it selects join points as
  271. based on the type of the formal parameter. So the pointcut
  272. [source, java]
  273. ....
  274. pointcut intArg(int i): args(i);
  275. ....
  276. picks out join points where an `int` (or a `byte`, `short`, or `char`;
  277. anything assignable to an `int`) is being passed as an argument. Second,
  278. though, it makes the value of that argument available to the enclosing
  279. advice or pointcut.
  280. Values can be exposed from named pointcuts as well, so
  281. [source, java]
  282. ....
  283. pointcut publicCall(int x): call(public *.*(int)) && intArg(x);
  284. pointcut intArg(int i): args(i);
  285. ....
  286. is a legal way to pick out all calls to public methods accepting an int
  287. argument, and exposing that argument.
  288. There is one special case for this kind of exposure. Exposing an
  289. argument of type Object will also match primitive typed arguments, and
  290. expose a "boxed" version of the primitive. So,
  291. [source, java]
  292. ....
  293. pointcut publicCall(): call(public *.*(..)) && args(Object);
  294. ....
  295. will pick out all unary methods that take, as their only argument,
  296. subtypes of Object (i.e., not primitive types like `int`), but
  297. [source, java]
  298. ....
  299. pointcut publicCall(Object o): call(public *.*(..)) && args(o);
  300. ....
  301. will pick out all unary methods that take any argument: And if the
  302. argument was an `int`, then the value passed to advice will be of type
  303. `java.lang.Integer`.
  304. The "boxing" of the primitive value is based on the _original_ primitive
  305. type. So in the following program
  306. [source, java]
  307. ....
  308. public class InstanceOf {
  309. public static void main(String[] args) {
  310. doInt(5);
  311. }
  312. static void doInt(int i) { }
  313. }
  314. aspect IntToLong {
  315. pointcut el(long l) :
  316. execution(* doInt(..)) && args(l);
  317. before(Object o) : el(o) {
  318. System.out.println(o.getClass());
  319. }
  320. }
  321. ....
  322. The pointcut will match and expose the integer argument, but it will
  323. expose it as an `Integer`, not a `Long`.
  324. === Primitive pointcuts
  325. ==== Method-related pointcuts
  326. AspectJ provides two primitive pointcut designators designed to capture
  327. method call and execution join points.
  328. * `call( MethodPattern )`
  329. * `execution( MethodPattern )`
  330. ==== Field-related pointcuts
  331. AspectJ provides two primitive pointcut designators designed to capture
  332. field reference and set join points:
  333. * `get( FieldPattern )`
  334. * `set( FieldPattern )`
  335. All set join points are treated as having one argument, the value the
  336. field is being set to, so at a set join point, that value can be
  337. accessed with an `args` pointcut. So an aspect guarding a static integer
  338. variable x declared in type T might be written as
  339. [source, java]
  340. ....
  341. aspect GuardedX {
  342. static final int MAX_CHANGE = 100;
  343. before(int newval): set(static int T.x) && args(newval) {
  344. if (Math.abs(newval - T.x) > MAX_CHANGE)
  345. throw new RuntimeException();
  346. }
  347. }
  348. ....
  349. ==== Object creation-related pointcuts
  350. AspectJ provides primitive pointcut designators designed to capture the
  351. initializer execution join points of objects.
  352. * `call( ConstructorPattern )`
  353. * `execution( ConstructorPattern )`
  354. * `initialization( ConstructorPattern )`
  355. * `preinitialization( ConstructorPattern )`
  356. ==== Class initialization-related pointcuts
  357. AspectJ provides one primitive pointcut designator to pick out static
  358. initializer execution join points.
  359. * `staticinitialization( TypePattern )`
  360. ==== Exception handler execution-related pointcuts
  361. AspectJ provides one primitive pointcut designator to capture execution
  362. of exception handlers:
  363. * `handler( TypePattern )`
  364. All handler join points are treated as having one argument, the value of
  365. the exception being handled. That value can be accessed with an `args`
  366. pointcut. So an aspect used to put `FooException` objects into some
  367. normal form before they are handled could be written as
  368. [source, java]
  369. ....
  370. aspect NormalizeFooException {
  371. before(FooException e): handler(FooException) && args(e) {
  372. e.normalize();
  373. }
  374. }
  375. ....
  376. ==== Advice execution-related pointcuts
  377. AspectJ provides one primitive pointcut designator to capture execution
  378. of advice
  379. * `adviceexecution()`
  380. This can be used, for example, to filter out any join point in the
  381. control flow of advice from a particular aspect.
  382. [source, java]
  383. ....
  384. aspect TraceStuff {
  385. pointcut myAdvice(): adviceexecution() && within(TraceStuff);
  386. before(): call(* *(..)) && !cflow(myAdvice) {
  387. // do something
  388. }
  389. }
  390. ....
  391. ==== State-based pointcuts
  392. Many concerns cut across the dynamic times when an object of a
  393. particular type is executing, being operated on, or being passed around.
  394. AspectJ provides primitive pointcuts that capture join points at these
  395. times. These pointcuts use the dynamic types of their objects to pick
  396. out join points. They may also be used to expose the objects used for
  397. discrimination.
  398. * `this( Type or Id )`
  399. * `target( Type or Id )`
  400. The `this` pointcut picks out each join point where the currently
  401. executing object (the object bound to `this`) is an instance of a
  402. particular type. The `target` pointcut picks out each join point where
  403. the target object (the object on which a method is called or a field is
  404. accessed) is an instance of a particular type. Note that `target` should
  405. be understood to be the object the current join point is transfering
  406. control to. This means that the target object is the same as the current
  407. object at a method execution join point, for example, but may be
  408. different at a method call join point.
  409. * `args( Type or Id or "..", ...)`
  410. The args pointcut picks out each join point where the arguments are
  411. instances of some types. Each element in the comma-separated list is one
  412. of four things. If it is a type name, then the argument in that position
  413. must be an instance of that type. If it is an identifier, then that
  414. identifier must be bound in the enclosing advice or pointcut
  415. declaration, and so the argument in that position must be an instance of
  416. the type of the identifier (or of any type if the identifier is typed to
  417. Object). If it is the `*` wildcard, then any argument will match, and if
  418. it is the special wildcard `..`, then any number of arguments will
  419. match, just like in signature patterns. So the pointcut
  420. [source, java]
  421. ....
  422. args(int, .., String)
  423. ....
  424. will pick out all join points where the first argument is an `int` and
  425. the last is a `String`.
  426. ==== Control flow-based pointcuts
  427. Some concerns cut across the control flow of the program. The `cflow`
  428. and `cflowbelow` primitive pointcut designators capture join points
  429. based on control flow.
  430. * `cflow( Pointcut )`
  431. * `cflowbelow( Pointcut )`
  432. The `cflow` pointcut picks out all join points that occur between entry
  433. and exit of each join point `P` picked out by `Pointcut`, including `P`
  434. itself. Hence, it picks out the join points _in_ the control flow of the
  435. join points picked out by `Pointcut`.
  436. The `cflowbelow` pointcut picks out all join points that occur between
  437. entry and exit of each join point `P` picked out by `Pointcut`, but not
  438. including `P` itself. Hence, it picks out the join points _below_ the
  439. control flow of the join points picked out by `Pointcut`.
  440. ===== Context exposure from control flows
  441. The `cflow` and `cflowbelow` pointcuts may expose context state through
  442. enclosed `this`, `target`, and `args` pointcuts.
  443. Anytime such state is accessed, it is accessed through the _most recent_
  444. control flow that matched. So the "current arg" that would be printed by
  445. the following program is zero, even though it is in many control flows.
  446. [source, java]
  447. ....
  448. class Test {
  449. public static void main(String[] args) {
  450. fact(5);
  451. }
  452. static int fact(int x) {
  453. if (x == 0) {
  454. System.err.println("bottoming out");
  455. return 1;
  456. }
  457. else return x * fact(x - 1);
  458. }
  459. }
  460. aspect A {
  461. pointcut entry(int i): call(int fact(int)) && args(i);
  462. pointcut writing(): call(void println(String)) && ! within(A);
  463. before(int i): writing() && cflow(entry(i)) {
  464. System.err.println("Current arg is " + i);
  465. }
  466. }
  467. ....
  468. It is an error to expose such state through _negated_ control flow
  469. pointcuts, such as within `!cflowbelow(P)`.
  470. ==== Program text-based pointcuts
  471. While many concerns cut across the runtime structure of the program,
  472. some must deal with the lexical structure. AspectJ allows aspects to
  473. pick out join points based on where their associated code is defined.
  474. * `within( TypePattern )`
  475. * `withincode( MethodPattern )`
  476. * `withincode( ConstructorPattern )`
  477. The `within` pointcut picks out each join point where the code executing
  478. is defined in the declaration of one of the types in `TypePattern`. This
  479. includes the class initialization, object initialization, and method and
  480. constructor execution join points for the type, as well as any join
  481. points associated with the statements and expressions of the type. It
  482. also includes any join points that are associated with code in a type's
  483. nested types, and that type's default constructor, if there is one.
  484. The `withincode` pointcuts picks out each join point where the code
  485. executing is defined in the declaration of a particular method or
  486. constructor. This includes the method or constructor execution join
  487. point as well as any join points associated with the statements and
  488. expressions of the method or constructor. It also includes any join
  489. points that are associated with code in a method or constructor's local
  490. or anonymous types.
  491. ==== Expression-based pointcuts
  492. * `if( BooleanExpression )`
  493. The if pointcut picks out join points based on a dynamic property. its
  494. syntax takes an expression, which must evaluate to a boolean true or
  495. false. Within this expression, the `thisJoinPoint` object is available.
  496. So one (extremely inefficient) way of picking out all call join points
  497. would be to use the pointcut
  498. [source, java]
  499. ....
  500. if(thisJoinPoint.getKind().equals("call"))
  501. ....
  502. Note that the order of evaluation for pointcut expression components at
  503. a join point is undefined. Writing `if` pointcuts that have side-effects
  504. is considered bad style and may also lead to potentially confusing or
  505. even changing behavior with regard to when or if the test code will run.
  506. === Signatures
  507. One very important property of a join point is its signature, which is
  508. used by many of AspectJ's pointcut designators to select particular join
  509. points.
  510. ==== Methods
  511. Join points associated with methods typically have method signatures,
  512. consisting of a method name, parameter types, return type, the types of
  513. the declared (checked) exceptions, and some type that the method could
  514. be called on (below called the "qualifying type").
  515. At a method call join point, the signature is a method signature whose
  516. qualifying type is the static type used to _access_ the method. This
  517. means that the signature for the join point created from the call
  518. `((Integer)i).toString()` is different than that for the call
  519. `((Object)i).toString()`, even if `i` is the same variable.
  520. At a method execution join point, the signature is a method signature
  521. whose qualifying type is the declaring type of the method.
  522. ==== Fields
  523. Join points associated with fields typically have field signatures,
  524. consisting of a field name and a field type. A field reference join
  525. point has such a signature, and no parameters. A field set join point
  526. has such a signature, but has a has a single parameter whose type is the
  527. same as the field type.
  528. ==== Constructors
  529. Join points associated with constructors typically have constructor
  530. signatures, consisting of a parameter types, the types of the declared
  531. (checked) exceptions, and the declaring type.
  532. At a constructor call join point, the signature is the constructor
  533. signature of the called constructor. At a constructor execution join
  534. point, the signature is the constructor signature of the currently
  535. executing constructor.
  536. At object initialization and pre-initialization join points, the
  537. signature is the constructor signature for the constructor that started
  538. this initialization: the first constructor entered during this type's
  539. initialization of this object.
  540. ==== Others
  541. At a handler execution join point, the signature is composed of the
  542. exception type that the handler handles.
  543. At an advice execution join point, the signature is composed of the
  544. aspect type, the parameter types of the advice, the return type (void
  545. for all but around advice) and the types of the declared (checked)
  546. exceptions.
  547. === Matching
  548. The `withincode`, `call`, `execution`, `get`, and `set` primitive
  549. pointcut designators all use signature patterns to determine the join
  550. points they describe. A signature pattern is an abstract description of
  551. one or more join-point signatures. Signature patterns are intended to
  552. match very closely the same kind of things one would write when
  553. declaring individual members and constructors.
  554. Method declarations in Java include method names, method parameters,
  555. return types, modifiers like static or private, and throws clauses,
  556. while constructor declarations omit the return type and replace the
  557. method name with the class name. The start of a particular method
  558. declaration, in class `Test`, for example, might be
  559. [source, java]
  560. ....
  561. class C {
  562. public final void foo() throws ArrayOutOfBoundsException { ... }
  563. }
  564. ....
  565. In AspectJ, method signature patterns have all these, but most elements
  566. can be replaced by wildcards. So
  567. [source, java]
  568. ....
  569. call(public final void C.foo() throws ArrayOutOfBoundsException)
  570. ....
  571. picks out call join points to that method, and the pointcut
  572. [source, java]
  573. ....
  574. call(public final void *.*() throws ArrayOutOfBoundsException)
  575. ....
  576. picks out all call join points to methods, regardless of their name name
  577. or which class they are defined on, so long as they take no arguments,
  578. return no value, are both `public` and `final`, and are declared to
  579. throw ``ArrayOutOfBoundsException``s.
  580. The defining type name, if not present, defaults to *, so another way of
  581. writing that pointcut would be
  582. [source, java]
  583. ....
  584. call(public final void *() throws ArrayOutOfBoundsException)
  585. ....
  586. The wildcard `..` indicates zero or more parameters, so
  587. [source, java]
  588. ....
  589. execution(void m(..))
  590. ....
  591. picks out execution join points for void methods named `m`, of any
  592. number of arguments, while
  593. [source, java]
  594. ....
  595. execution(void m(.., int))
  596. ....
  597. picks out execution join points for void methods named `m` whose last
  598. parameter is of type `int`.
  599. The modifiers also form part of the signature pattern. If an AspectJ
  600. signature pattern should match methods without a particular modifier,
  601. such as all non-public methods, the appropriate modifier should be
  602. negated with the `!` operator. So,
  603. [source, java]
  604. ....
  605. withincode(!public void foo())
  606. ....
  607. picks out all join points associated with code in null non-public void
  608. methods named `foo`, while
  609. [source, java]
  610. ....
  611. withincode(void foo())
  612. ....
  613. picks out all join points associated with code in null void methods
  614. named `foo`, regardless of access modifier.
  615. Method names may contain the * wildcard, indicating any number of
  616. characters in the method name. So
  617. [source, java]
  618. ....
  619. call(int *())
  620. ....
  621. picks out all call join points to `int` methods regardless of name, but
  622. [source, java]
  623. ....
  624. call(int get*())
  625. ....
  626. picks out all call join points to `int` methods where the method name
  627. starts with the characters "get".
  628. AspectJ uses the `new` keyword for constructor signature patterns rather
  629. than using a particular class name. So the execution join points of
  630. private null constructor of a class `C` defined to throw an
  631. `ArithmeticException` can be picked out with
  632. [source, java]
  633. ....
  634. execution(private C.new() throws ArithmeticException)
  635. ....
  636. ==== Matching based on the declaring type
  637. The signature-matching pointcuts all specify a declaring type, but the
  638. meaning varies slightly for each join point signature, in line with Java
  639. semantics.
  640. When matching for pointcuts `withincode`, `get`, and `set`, the
  641. declaring type is the class that contains the declaration.
  642. When matching method-call join points, the declaring type is the static
  643. type used to access the method. A common mistake is to specify a
  644. declaring type for the `call` pointcut that is a subtype of the
  645. originally-declaring type. For example, given the class
  646. [source, java]
  647. ....
  648. class Service implements Runnable {
  649. public void run() { ... }
  650. }
  651. ....
  652. the following pointcut
  653. [source, java]
  654. ....
  655. call(void Service.run())
  656. ....
  657. would fail to pick out the join point for the code
  658. [source, java]
  659. ....
  660. ((Runnable) new Service()).run();
  661. ....
  662. Specifying the originally-declaring type is correct, but would pick out
  663. any such call (here, calls to the `run()` method of any `Runnable`). In
  664. this situation, consider instead picking out the target type:
  665. [source, java]
  666. ....
  667. call(void run()) && target(Service)
  668. ....
  669. When matching method-execution join points, if the execution pointcut
  670. method signature specifies a declaring type, the pointcut will only
  671. match methods declared in that type, or methods that override methods
  672. declared in or inherited by that type. So the pointcut
  673. [source, java]
  674. ....
  675. execution(public void Middle.*())
  676. ....
  677. picks out all method executions for public methods returning void and
  678. having no arguments that are either declared in, or inherited by,
  679. `Middle`, even if those methods are overridden in a subclass of `Middle`. So
  680. the pointcut would pick out the method-execution join point for `Sub.m()`
  681. in this code:
  682. [source, java]
  683. ....
  684. class Super {
  685. protected void m() { /*...*/ }
  686. }
  687. class Middle extends Super {}
  688. class Sub extends Middle {
  689. public void m() { /*...*/ }
  690. }
  691. ....
  692. ==== Matching based on the `throws` clause
  693. Type patterns may be used to pick out methods and constructors based on
  694. their `throws` clauses. This allows the following two kinds of extremely
  695. wildcarded pointcuts:
  696. [source, java]
  697. ....
  698. pointcut throwsMathlike():
  699. // each call to a method with a throws clause containing at least
  700. // one exception exception with "Math" in its name.
  701. call(* *(..) throws *..*Math*);
  702. pointcut doesNotThrowMathlike():
  703. // each call to a method with a throws clause containing no
  704. // exceptions with "Math" in its name.
  705. call(* *(..) throws !*..*Math*);
  706. ....
  707. A `ThrowsClausePattern` is a comma-separated list of ``ThrowsClausePatternItem``s, where
  708. [source, text]
  709. ....
  710. ThrowsClausePatternItem := [ ! ] TypeNamePattern
  711. ....
  712. A `ThrowsClausePattern` matches the `throws` clause of any code member
  713. signature. To match, each `ThrowsClausePatternItem` must match the
  714. `throws` clause of the member in question. If any item doesn't match, then
  715. the whole pattern doesn't match.
  716. If a `ThrowsClausePatternItem` begins with `!`, then it matches a
  717. particular `throws` clause if and only if _none_ of the types named in the
  718. `throws` clause is matched by the `TypeNamePattern`.
  719. If a `ThrowsClausePatternItem` does not begin with `!`, then it matches
  720. a throws clause if and only if _any_ of the types named in the `throws`
  721. clause is matched by the `TypeNamePattern`.
  722. The rule for `!` matching has one potentially surprising property, in
  723. that these two pointcuts
  724. . `call(* *(..) throws !IOException)`
  725. . `call(* *(..) throws (!IOException))`
  726. will match differently on calls to
  727. [source, java]
  728. ....
  729. void m() throws RuntimeException, IOException {}
  730. ....
  731. [1] will *not* match the method `m()`, because ``m``'s throws clause
  732. declares that it `throws IOException`.
  733. [2] *will* match the method `m()`, because ``m``'s throws clause declares that
  734. it throws some exception which does not match `IOException`, i.e. `RuntimeException`.
  735. === Type patterns
  736. Type patterns are a way to pick out collections of types and use them in
  737. places where you would otherwise use only one type. The rules for using
  738. type patterns are simple.
  739. ==== Exact type pattern
  740. First, all type names are also type patterns. So `Object`,
  741. `java.util.HashMap`, `Map.Entry`, `int` are all type patterns.
  742. If a type pattern is an exact type - if it doesn't include a wildcard -
  743. then the matching works just like normal type lookup in Java:
  744. * Patterns that have the same names as primitive types (like `int`) match those
  745. primitive types.
  746. * Patterns that are qualified by package names (like `java.util.HashMap`) match
  747. types in other packages.
  748. * Patterns that are not qualified (like `HashMap`) match types that are resolved
  749. by Java's normal scope rules. So, for example, `HashMap` might match a package-level
  750. type in the same package or a type that have been imported with Java's `import`
  751. form. But it would not match `java.util.HashMap` unless the aspect were in `java.util`
  752. or the type had been imported.
  753. So exact type patterns match based on usual Java scope rules.
  754. ==== Type name patterns
  755. There is a special type name, `\*`, which is also a type pattern. `*` picks
  756. out all types, including primitive types. So
  757. [source, java]
  758. ....
  759. call(void foo(*))
  760. ....
  761. picks out all call join points to void methods named foo, taking one
  762. argument of any type.
  763. Type names that contain the two wildcards `\*` and `..` are also type
  764. patterns. The `*` wildcard matches zero or more characters characters
  765. except for `.`, so it can be used when types have a certain naming
  766. convention. So
  767. [source, java]
  768. ....
  769. handler(java.util.*Map)
  770. ....
  771. picks out the types `java.util.Map` and `java.util.java.util.HashMap`, among
  772. others, and
  773. [source, java]
  774. ....
  775. handler(java.util.*)
  776. ....
  777. picks out all types that start with `java.util.` and don't have any
  778. more ``.``s, that is, the types in the `java.util` package, but not inner
  779. types (such as `java.util.Map.Entry`).
  780. The `..` wildcard matches any sequence of characters that start and
  781. end with a `.`, so it can be used to pick out all types in any
  782. subpackage, or all inner types. So
  783. [source, java]
  784. ....
  785. within(com.xerox..*)
  786. ....
  787. picks out all join points where the code is in any declaration of a type
  788. whose name begins with `com.xerox.`.
  789. Type patterns with wildcards do not depend on Java's usual scope rules -
  790. they match against all types available to the weaver, not just those
  791. that are imported into an Aspect's declaring file.
  792. ==== Subtype patterns
  793. It is possible to pick out all subtypes of a type (or a collection of
  794. types) with the `+` wildcard. The `+` wildcard follows immediately a
  795. type name pattern. So, while
  796. [source, java]
  797. ....
  798. call(Foo.new())
  799. ....
  800. picks out all constructor call join points where an instance of exactly
  801. type `Foo` is constructed,
  802. [source, java]
  803. ....
  804. call(Foo+.new())
  805. ....
  806. picks out all constructor call join points where an instance of any
  807. subtype of `Foo` (including `Foo` itself) is constructed, and the unlikely
  808. [source, java]
  809. ....
  810. call(*Handler+.new())
  811. ....
  812. picks out all constructor call join points where an instance of any
  813. subtype of any type whose name ends in `Handler` is constructed.
  814. ==== Array type patterns
  815. A type name pattern or subtype pattern can be followed by one or more
  816. sets of square brackets to make array type patterns. So `Object[]` is an
  817. array type pattern, and so is `com.xerox..*[][]`, and so is `Object+[]`.
  818. ==== Type patterns
  819. Type patterns are built up out of type name patterns, subtype patterns,
  820. and array type patterns, and constructed with boolean operators `&&`,
  821. `||`, and `!`. So
  822. [source, java]
  823. ....
  824. staticinitialization(Foo || Bar)
  825. ....
  826. picks out the static initializer execution join points of either `Foo` or
  827. `Bar`, and
  828. [source, java]
  829. ....
  830. call((Foo+ && ! Foo).new(..))
  831. ....
  832. picks out the constructor call join points when a subtype of `Foo`, but
  833. not `Foo` itself, is constructed.
  834. === Pattern Summary
  835. Here is a summary of the pattern syntax used in AspectJ:
  836. [source, text]
  837. ....
  838. MethodPattern =
  839. [ModifiersPattern] TypePattern
  840. [TypePattern . ] IdPattern (TypePattern | ".." , ... )
  841. [ throws ThrowsPattern ]
  842. ConstructorPattern =
  843. [ModifiersPattern ]
  844. [TypePattern . ] new (TypePattern | ".." , ...)
  845. [ throws ThrowsPattern ]
  846. FieldPattern =
  847. [ModifiersPattern] TypePattern [TypePattern . ] IdPattern
  848. ThrowsPattern =
  849. [ ! ] TypePattern , ...
  850. TypePattern =
  851. IdPattern [ + ] [ [] ... ]
  852. | ! TypePattern
  853. | TypePattern && TypePattern
  854. | TypePattern || TypePattern
  855. | ( TypePattern )
  856. IdPattern =
  857. Sequence of characters, possibly with special * and .. wildcards
  858. ModifiersPattern =
  859. [ ! ] JavaModifier ...
  860. ....
  861. [[semantics-advice]]
  862. == Advice
  863. Each piece of advice is of the form
  864. [source, text]
  865. ....
  866. [ strictfp ] AdviceSpec [ throws TypeList ] : Pointcut { Body }
  867. ....
  868. where `AdviceSpec` is one of
  869. * `before( Formals )`
  870. * `after( Formals ) returning [ ( Formal ) ]`
  871. * `after( Formals ) throwing [ ( Formal ) ]`
  872. * `after( Formals )`
  873. * `Type around( Formals )`
  874. and where `Formal` refers to a variable binding like those used for
  875. method parameters, of the form `Type` `Variable-Name`, and `Formals`
  876. refers to a comma-delimited list of `Formal`.
  877. Advice defines crosscutting behavior. It is defined in terms of
  878. pointcuts. The code of a piece of advice runs at every join point picked
  879. out by its pointcut. Exactly how the code runs depends on the kind of
  880. advice.
  881. AspectJ supports three kinds of advice. The kind of advice determines
  882. how it interacts with the join points it is defined over. Thus AspectJ
  883. divides advice into that which runs *before* its join points, that which
  884. runs *after* its join points, and that which runs *in place of (or
  885. "around")* its join points.
  886. While `before` advice is relatively unproblematic, there can be three
  887. interpretations of `after` advice: After the execution of a join point
  888. completes normally, after it throws an exception, or after it does
  889. either one. AspectJ allows `after` advice for any of these situations:
  890. [source, java]
  891. ....
  892. aspect A {
  893. pointcut publicCall(): call(public Object *(..));
  894. after() returning (Object o): publicCall() {
  895. System.out.println("Returned normally with " + o);
  896. }
  897. after() throwing (Exception e): publicCall() {
  898. System.out.println("Threw an exception: " + e);
  899. }
  900. after(): publicCall(){
  901. System.out.println("Returned or threw an Exception");
  902. }
  903. }
  904. ....
  905. `after returning` advice may not care about its returned object, in which
  906. case it may be written
  907. [source, java]
  908. ....
  909. after() returning: call(public Object *(..)) {
  910. System.out.println("Returned normally");
  911. }
  912. ....
  913. If `after returning` does expose its returned object, then the type of the
  914. parameter is considered to be an `instanceof`-like constraint on the
  915. advice: it will run only when the return value is of the appropriate
  916. type.
  917. A value is of the appropriate type if it would be assignable to a
  918. variable of that type, in the Java sense. That is, a `byte` value is
  919. assignable to a `short` parameter but not vice-versa, an `int` is
  920. assignable to a `float` parameter, `boolean` values are only assignable
  921. to `boolean` parameters, and reference types work by `instanceof`.
  922. There are two special cases: If the exposed value is typed to `Object`,
  923. then the advice is not constrained by that type: the actual return value
  924. is converted to an object type for the body of the advice: `int` values
  925. are represented as `java.lang.Integer` objects, etc, and no value (from
  926. `void` methods, for example) is represented as `null`.
  927. Secondly, the `null` value is assignable to a parameter `T` if the join
  928. point _could_ return something of type `T`.
  929. `around` advice runs in place of the join point it operates over, rather
  930. than before or after it. Because `around` is allowed to return a value, it
  931. must be declared with a return type, like a method.
  932. Thus, a simple use of `around` advice is to make a particular method
  933. constant:
  934. [source, java]
  935. ....
  936. aspect A {
  937. int around(): call(int C.foo()) {
  938. return 3;
  939. }
  940. }
  941. ....
  942. Within the body of `around` advice, though, the computation of the
  943. original join point can be executed with the special syntax
  944. [source, java]
  945. ....
  946. proceed( ... )
  947. ....
  948. The `proceed` form takes as arguments the context exposed by the around's
  949. pointcut, and returns whatever the around is declared to return. So the
  950. following around advice will double the second argument to `foo`
  951. whenever it is called, and then halve its result:
  952. [source, java]
  953. ....
  954. aspect A {
  955. int around(int i): call(int C.foo(Object, int)) && args(i) {
  956. int newi = proceed(i*2)
  957. return newi/2;
  958. }
  959. }
  960. ....
  961. If the return value of `around` advice is typed to `Object`, then the
  962. result of proceed is converted to an object representation, even if it
  963. is originally a primitive value. And when the advice returns an `Object`
  964. value, that value is converted back to whatever representation it was
  965. originally. So another way to write the doubling and halving advice is:
  966. [source, java]
  967. ....
  968. aspect A {
  969. Object around(int i): call(int C.foo(Object, int)) && args(i) {
  970. Integer newi = (Integer) proceed(i*2)
  971. return new Integer(newi.intValue() / 2);
  972. }
  973. }
  974. ....
  975. Any occurence of `proceed(..)` within the body of around advice is
  976. treated as the special `proceed` form (even if the aspect defines a method
  977. named `proceed`), unless a target other than the aspect instance is
  978. specified as the recipient of the call. For example, in the following
  979. program the first call to `proceed` will be treated as a method call to
  980. the `ICanProceed` instance, whereas the second call to `proceed` is
  981. treated as the special `proceed` form.
  982. [source, java]
  983. ....
  984. aspect A {
  985. Object around(ICanProceed canProceed) : execution(* *(..)) && this(canProceed) {
  986. canProceed.proceed(); // a method call
  987. return proceed(canProceed); // the special proceed form
  988. }
  989. private Object proceed(ICanProceed canProceed) {
  990. // this method cannot be called from inside the body of around advice
  991. // in the aspect
  992. }
  993. }
  994. ....
  995. In all kinds of advice, the parameters of the advice behave exactly like
  996. method parameters. In particular, assigning to any parameter affects
  997. only the value of the parameter, not the value that it came from. This
  998. means that
  999. [source, java]
  1000. ....
  1001. aspect A {
  1002. after() returning (int i): call(int C.foo()) {
  1003. i = i * 2;
  1004. }
  1005. }
  1006. ....
  1007. will _not_ double the returned value of the advice. Rather, it will
  1008. double the local parameter. Changing the values of parameters or return
  1009. values of join points can be done by using `around` advice.
  1010. With `proceed(..)` it is possible to change the values used by
  1011. less-precedent advice and the underlying join point by supplying
  1012. different values for the variables. For example, this aspect replaces
  1013. the string bound to `s` in the named pointcut `privateData`:
  1014. [source, java]
  1015. ....
  1016. aspect A {
  1017. Object around(String s): MyPointcuts.privateData(s) {
  1018. return proceed("private data");
  1019. }
  1020. }
  1021. ....
  1022. If you replace an argument to `proceed(..)`, you can cause a
  1023. `ClassCastException` at runtime when the argument refers to a supertype
  1024. of the actual type and you do not supply a reference of the actual type.
  1025. In the following aspect, the around advice replaces the declared target
  1026. `List` with an `ArrayList`. This is valid code at compile-time since the
  1027. types match.
  1028. [source, java]
  1029. ....
  1030. import java.util.*;
  1031. aspect A {
  1032. Object around(List list): call(* List+.*()) && target(list) {
  1033. return proceed(new ArrayList());
  1034. }
  1035. }
  1036. ....
  1037. But imagine a simple program where the actual target is `LinkedList`. In
  1038. this case, the advice would cause a `ClassCastException` at runtime, and
  1039. `peek()` is not declared in `ArrayList`.
  1040. [source, java]
  1041. ....
  1042. public class Test {
  1043. public static void main(String[] args) {
  1044. new LinkedList().peek();
  1045. }
  1046. }
  1047. ....
  1048. The `ClassCastException` can occur even in situations where it appears
  1049. to be unnecessary, e.g., if the program is changed to call `size()`,
  1050. declared in `List`:
  1051. [source, java]
  1052. ....
  1053. public class Test {
  1054. public static void main(String[] args) {
  1055. new LinkedList().size();
  1056. }
  1057. }
  1058. ....
  1059. There will still be a `ClassCastException` because it is impossible to
  1060. prove that there won't be a runtime binary-compatible change in the
  1061. hierarchy of `LinkedList` or some other advice on the join point that
  1062. requires a `LinkedList`.
  1063. === Advice modifiers
  1064. The `strictfp` modifier is the only modifier allowed on advice, and it
  1065. has the effect of making all floating-point expressions within the
  1066. advice be FP-strict.
  1067. === Advice and checked exceptions
  1068. An advice declaration must include a `throws` clause listing the checked
  1069. exceptions the body may throw. This list of checked exceptions must be
  1070. compatible with each target join point of the advice, or an error is
  1071. signalled by the compiler.
  1072. For example, in the following declarations:
  1073. [source, java]
  1074. ....
  1075. import java.io.FileNotFoundException;
  1076. class C {
  1077. int i;
  1078. int getI() { return i; }
  1079. }
  1080. aspect A {
  1081. before(): get(int C.i) {
  1082. throw new FileNotFoundException();
  1083. }
  1084. before() throws FileNotFoundException: get(int C.i) {
  1085. throw new FileNotFoundException();
  1086. }
  1087. }
  1088. ....
  1089. both pieces of advice are illegal. The first because the body throws an
  1090. undeclared checked exception, and the second because field get join
  1091. points cannot throw ``FileNotFoundException``s.
  1092. The exceptions that each kind of join point in AspectJ may throw are:
  1093. method call and execution::
  1094. the checked exceptions declared by the target method's `throws` clause.
  1095. constructor call and execution::
  1096. the checked exceptions declared by the target constructor's `throws` clause.
  1097. field get and set::
  1098. no checked exceptions can be thrown from these join points.
  1099. exception handler execution::
  1100. the exceptions that can be thrown by the target exception handler.
  1101. static initializer execution::
  1102. no checked exceptions can be thrown from these join points.
  1103. pre-initialization and initialization::
  1104. any exception that is in the `throws` clause of all constructors of the initialized class.
  1105. advice execution::
  1106. any exception that is in the `throws` clause of the advice.
  1107. === Advice precedence
  1108. Multiple pieces of advice may apply to the same join point. In such
  1109. cases, the resolution order of the advice is based on advice precedence.
  1110. ==== Determining precedence
  1111. There are a number of rules that determine whether a particular piece of
  1112. advice has precedence over another when they advise the same join point.
  1113. If the two pieces of advice are defined in different aspects, then there
  1114. are three cases:
  1115. * If aspect `A` is matched earlier than aspect `B` in some `declare precedence`
  1116. form, then all advice in concrete aspect `A` has precedence over all
  1117. advice in concrete aspect `B` when they are on the same join point.
  1118. * Otherwise, if aspect `A` is a subaspect of aspect `B`, then all advice
  1119. defined in `A` has precedence over all advice defined in `B`. So, unless
  1120. otherwise specified with `declare precedence`, advice in a subaspect has
  1121. precedence over advice in a superaspect.
  1122. * Otherwise, if two pieces of advice are defined in two different
  1123. aspects, it is undefined which one has precedence.
  1124. If the two pieces of advice are defined in the same aspect, then there
  1125. are two cases:
  1126. * If either are `after` advice, then the one that appears later in the aspect has precedence
  1127. over the one that appears earlier.
  1128. * Otherwise, then the one that appears earlier in the aspect has
  1129. precedence over the one that appears later.
  1130. These rules can lead to circularity, such as
  1131. [source, java]
  1132. ....
  1133. aspect A {
  1134. before(): execution(void main(String[] args)) {}
  1135. after(): execution(void main(String[] args)) {}
  1136. before(): execution(void main(String[] args)) {}
  1137. }
  1138. ....
  1139. such circularities will result in errors signalled by the compiler.
  1140. ==== Effects of precedence
  1141. At a particular join point, advice is ordered by precedence.
  1142. A piece of `around` advice controls whether advice of lower precedence
  1143. will run by calling `proceed`. The call to `proceed` will run the advice
  1144. with next precedence, or the computation under the join point if there
  1145. is no further advice.
  1146. A piece of `before` advice can prevent advice of lower precedence from
  1147. running by throwing an exception. If it returns normally, however, then
  1148. the advice of the next precedence, or the computation under the join
  1149. pint if there is no further advice, will run.
  1150. Running `after returning` advice will run the advice of next precedence,
  1151. or the computation under the join point if there is no further advice.
  1152. Then, if that computation returned normally, the body of the advice will
  1153. run.
  1154. Running `after throwing` advice will run the advice of next precedence,
  1155. or the computation under the join point if there is no further advice.
  1156. Then, if that computation threw an exception of an appropriate type, the
  1157. body of the advice will run.
  1158. Running `after` advice will run the advice of next precedence, or the
  1159. computation under the join point if there is no further advice. Then the
  1160. body of the advice will run.
  1161. === Reflective access to the join point
  1162. Three special variables are visible within bodies of advice and within
  1163. `if()` pointcut expressions: `thisJoinPoint`, `thisJoinPointStaticPart`,
  1164. and `thisEnclosingJoinPointStaticPart`. Each is bound to an object that
  1165. encapsulates some of the context of the advice's current or enclosing
  1166. join point. These variables exist because some pointcuts may pick out
  1167. very large collections of join points. For example, the pointcut
  1168. [source, java]
  1169. ....
  1170. pointcut publicCall(): call(public * *(..));
  1171. ....
  1172. picks out calls to many methods. Yet the body of advice over this
  1173. pointcut may wish to have access to the method name or parameters of a
  1174. particular join point.
  1175. * `thisJoinPoint` is bound to a complete join point object.
  1176. * `thisJoinPointStaticPart` is bound to a part of the join point object
  1177. that includes less information, but for which no memory allocation is
  1178. required on each execution of the advice. It is equivalent to
  1179. `thisJoinPoint.getStaticPart()`.
  1180. * `thisEnclosingJoinPointStaticPart` is bound to the static part of the
  1181. join point enclosing the current join point. Only the static part of
  1182. this enclosing join point is available through this mechanism.
  1183. Standard Java reflection uses objects from the `java.lang.reflect`
  1184. hierarchy to build up its reflective objects. Similarly, AspectJ join
  1185. point objects have types in a type hierarchy. The type of objects bound
  1186. to `thisJoinPoint` is `org.aspectj.lang.JoinPoint`, while
  1187. `thisStaticJoinPoint` is bound to objects of interface type
  1188. `org.aspectj.lang.JoinPoint.StaticPart`.
  1189. [[semantics-declare]]
  1190. == Static crosscutting
  1191. Advice declarations change the behavior of classes they crosscut, but do
  1192. not change their static type structure. For crosscutting concerns that
  1193. do operate over the static structure of type hierarchies, AspectJ
  1194. provides inter-type member declarations and other `declare` forms.
  1195. === Inter-type member declarations
  1196. AspectJ allows the declaration of members by aspects that are associated
  1197. with other types.
  1198. An inter-type method declaration looks like
  1199. * `[ Modifiers ] Type OnType . Id ( Formals ) [ ThrowsClause ] { Body }`
  1200. * `abstract [ Modifiers ] Type OnType . Id ( Formals ) [ ThrowsClause ] ;`
  1201. The effect of such a declaration is to make `OnType` support the new
  1202. method. Even if `OnType` is an interface. Even if the method is neither
  1203. public nor abstract. So the following is legal AspectJ code:
  1204. [source, java]
  1205. ....
  1206. interface Iface {}
  1207. aspect A {
  1208. private void Iface.m() {
  1209. System.err.println("I'm a private method on an interface");
  1210. }
  1211. void worksOnI(Iface iface) {
  1212. // calling a private method on an interface
  1213. iface.m();
  1214. }
  1215. }
  1216. ....
  1217. An inter-type constructor declaration looks like
  1218. * `[ Modifiers ] OnType . new ( Formals ) [ ThrowsClause ] { Body }`
  1219. The effect of such a declaration is to make `OnType` support the new
  1220. constructor. It is an error for `OnType` to be an interface.
  1221. Inter-type declared constructors cannot be used to assign a value to a
  1222. final variable declared in `OnType`. This limitation significantly
  1223. increases the ability to both understand and compile the `OnType` class
  1224. and the declaring aspect separately.
  1225. Note that in the Java language, classes that define no constructors have
  1226. an implicit no-argument constructor that just calls `super()`. This
  1227. means that attempting to declare a no-argument inter-type constructor on
  1228. such a class may result in a conflict, even though it _looks_ like no
  1229. constructor is defined.
  1230. An inter-type field declaration looks like one of
  1231. * `[ Modifiers ] Type OnType . Id = Expression ;`
  1232. * `[ Modifiers ] Type OnType . Id ;`
  1233. The effect of such a declaration is to make `OnType` support the new
  1234. field. Even if `OnType` is an interface. Even if the field is neither
  1235. public, nor static, nor final.
  1236. The initializer, if any, of an inter-type field declaration runs before
  1237. the class-local initializers defined in its target class.
  1238. Any occurrence of the identifier `this` in the body of an inter-type
  1239. constructor or method declaration, or in the initializer of an
  1240. inter-type field declaration, refers to the `OnType` object rather than
  1241. to the aspect type; it is an error to access `this` in such a position
  1242. from a `static` inter-type member declaration.
  1243. === Access modifiers
  1244. Inter-type member declarations may be `public` or `private`, or have default
  1245. (package-protected) visibility. AspectJ does not provide protected
  1246. inter-type members.
  1247. The access modifier applies in relation to the aspect, not in relation
  1248. to the target type. So a private inter-type member is visible only from
  1249. code that is defined within the declaring aspect. A default-visibility
  1250. inter-type member is visible only from code that is defined within the
  1251. declaring aspect's package.
  1252. Note that a declaring a private inter-type method (which AspectJ
  1253. supports) is very different from inserting a private method declaration
  1254. into another class. The former allows access only from the declaring
  1255. aspect, while the latter would allow access only from the target type.
  1256. Java serialization, for example, uses the presense of a private method
  1257. `void writeObject(ObjectOutputStream)` for the implementation of
  1258. `java.io.Serializable`. A private inter-type declaration of that method
  1259. would not fulfill this requirement, since it would be private to the
  1260. aspect, not private to the target type.
  1261. The access modifier of abstract inter-type methods has one constraint:
  1262. It is illegal to declare an abstract non-public inter-type method on a
  1263. public interface. This is illegal because it would say that a public
  1264. interface has a constraint that only non-public implementors must
  1265. fulfill. This would not be compatible with Java's type system.
  1266. === Conflicts
  1267. Inter-type declarations raise the possibility of conflicts among locally
  1268. declared members and inter-type members. For example, assuming
  1269. `otherPackage` is not the package containing the aspect `A`, the code
  1270. [source, java]
  1271. ....
  1272. aspect A {
  1273. private Registry otherPackage.onType.r;
  1274. public void otherPackage.onType.register(Registry r) {
  1275. r.register(this);
  1276. this.r = r;
  1277. }
  1278. }
  1279. ....
  1280. declares that `onType` in `otherPackage` has a field `r`. This field,
  1281. however, is only accessible from the code inside of aspect `A`. The
  1282. aspect also declares that `onType` has a method "`register`", but makes
  1283. this method accessible from everywhere.
  1284. If `onType` already defines a private or package-protected field `r`,
  1285. there is no conflict: The aspect cannot see such a field, and no code in
  1286. `otherPackage` can see the inter-type `r`.
  1287. If `onType` defines a public field `r`, there is a conflict: The
  1288. expression
  1289. [source, java]
  1290. ....
  1291. this.r = r
  1292. ....
  1293. is an error, since it is ambiguous whether the private inter-type `r`
  1294. or the public locally-defined `r` should be used.
  1295. If `onType` defines a method `register(Registry)` there is a conflict,
  1296. since it would be ambiguous to any code that could see such a defined
  1297. method which `register(Registry)` method was applicable.
  1298. Conflicts are resolved as much as possible as per Java's conflict
  1299. resolution rules:
  1300. * A subclass can inherit multiple fields from its superclasses, all with the
  1301. same name and type. However, it is an error to have an ambiguous reference
  1302. to a field.
  1303. * A subclass can only inherit multiple methods with the same name and argument
  1304. types from its superclasses if only zero or one of them is concrete (i.e., all
  1305. but one is abstract, or all are abstract).
  1306. Given a potential conflict between inter-type member declarations in
  1307. different aspects, if one aspect has precedence over the other its
  1308. declaration will take effect without any conflict notice from compiler.
  1309. This is true both when the precedence is declared explicitly with
  1310. `declare precedence` as well as when when sub-aspects implicitly have
  1311. precedence over their super-aspect.
  1312. === Extension and Implementation
  1313. An aspect may change the inheritance hierarchy of a system by changing
  1314. the superclass of a type or adding a superinterface onto a type, with
  1315. the `declare parents` form.
  1316. * `declare parents: TypePattern extends Type ;`
  1317. * `declare parents: TypePattern implements TypeList ;`
  1318. For example, if an aspect wished to make a particular class runnable, it
  1319. might define appropriate inter-type `void
  1320. run()` method, but it should also declare that the class
  1321. fulfills the `Runnable` interface. In order to implement the methods in
  1322. the `Runnable` interface, the inter-type `run()` method must be public:
  1323. [source, java]
  1324. ....
  1325. aspect A {
  1326. declare parents: SomeClass implements Runnable;
  1327. public void SomeClass.run() { ... }
  1328. }
  1329. ....
  1330. === Interfaces with members
  1331. Through the use of inter-type members, interfaces may now carry
  1332. (non-public-static-final) fields and (non-public-abstract) methods that
  1333. classes can inherit. Conflicts may occur from ambiguously inheriting
  1334. members from a superclass and multiple superinterfaces.
  1335. Because interfaces may carry non-static initializers, each interface
  1336. behaves as if it has a zero-argument constructor containing its
  1337. initializers. The order of super-interface instantiation is observable.
  1338. We fix this order with the following properties: A supertype is
  1339. initialized before a subtype, initialized code runs only once, and the
  1340. initializers for a type's superclass are run before the initializers for
  1341. its superinterfaces. Consider the following hierarchy where {`Object`,
  1342. `C`, `D`, `E`} are classes, {`M`, `N`, `O`, `P`, `Q`} are interfaces.
  1343. [source, text]
  1344. ....
  1345. Object M O
  1346. \ / \ /
  1347. C N Q
  1348. \ / /
  1349. D P
  1350. \ /
  1351. E
  1352. ....
  1353. when a new `E` is instantiated, the initializers run in this order:
  1354. [source, text]
  1355. ....
  1356. Object M C O N D Q P E
  1357. ....
  1358. === Warnings and Errors
  1359. An aspect may specify that a particular join point should never be
  1360. reached.
  1361. * `declare error: Pointcut : String ;`
  1362. * `declare warning: Pointcut : String ;`
  1363. If the compiler determines that a join point in `Pointcut` could
  1364. possibly be reached, then it will signal either an error or warning, as
  1365. declared, using the `String` for its message.
  1366. === Softened exceptions
  1367. An aspect may specify that a particular kind of exception, if thrown at
  1368. a join point, should bypass Java's usual static exception checking
  1369. system and instead be thrown as a `org.aspectj.lang.SoftException`,
  1370. which is subtype of `RuntimeException` and thus does not need to be
  1371. declared.
  1372. * `declare soft: Type : Pointcut ;`
  1373. For example, the aspect
  1374. [source, java]
  1375. ....
  1376. aspect A {
  1377. declare soft: Exception: execution(void main(String[] args));
  1378. }
  1379. ....
  1380. Would, at the execution join point, catch any `Exception` and rethrow a
  1381. `org.aspectj.lang.SoftException` containing original exception.
  1382. This is similar to what the following advice would do
  1383. [source, java]
  1384. ....
  1385. aspect A {
  1386. void around() execution(void main(String[] args)) {
  1387. try { proceed(); }
  1388. catch (Exception e) {
  1389. throw new org.aspectj.lang.SoftException(e);
  1390. }
  1391. }
  1392. }
  1393. ....
  1394. except, in addition to wrapping the exception, it also affects Java's
  1395. static exception checking mechanism.
  1396. Like advice, the declare soft form has no effect in an abstract aspect
  1397. that is not extended by a concreate aspect. So the following code will
  1398. not compile unless it is compiled with an extending concrete aspect:
  1399. [source, java]
  1400. ....
  1401. abstract aspect A {
  1402. abstract pointcut softeningPC();
  1403. before() : softeningPC() {
  1404. Class.forName("FooClass"); // error: uncaught ClassNotFoundException
  1405. }
  1406. declare soft : ClassNotFoundException : call(* Class.*(..));
  1407. }
  1408. ....
  1409. [[advice-precedence-cross]]
  1410. === Advice Precedence
  1411. An aspect may declare a precedence relationship between concrete aspects
  1412. with the `declare precedence` form:
  1413. * `declare precedence : TypePatternList ;`
  1414. This signifies that if any join point has advice from two concrete
  1415. aspects matched by some pattern in `TypePatternList`, then the
  1416. precedence of the advice will be the order of in the list.
  1417. In `TypePatternList`, the wildcard `*` can appear at most once, and it
  1418. means "any type not matched by any other pattern in the list".
  1419. For example, the constraints that (1) aspects that have Security as part
  1420. of their name should have precedence over all other aspects, and (2) the
  1421. Logging aspect (and any aspect that extends it) should have precedence
  1422. over all non-security aspects, can be expressed by:
  1423. [source, java]
  1424. ....
  1425. declare precedence: *..*Security*, Logging+, *;
  1426. ....
  1427. For another example, the `CountEntry` aspect might want to count the entry
  1428. to methods in the current package accepting a Type object as its first
  1429. argument. However, it should count all entries, even those that the
  1430. aspect `DisallowNulls` causes to throw exceptions. This can be
  1431. accomplished by stating that `CountEntry` has precedence over
  1432. `DisallowNulls`. This declaration could be in either aspect, or in
  1433. another, ordering aspect:
  1434. [source, java]
  1435. ....
  1436. aspect Ordering {
  1437. declare precedence: CountEntry, DisallowNulls;
  1438. }
  1439. aspect DisallowNulls {
  1440. pointcut allTypeMethods(Type obj): call(* *(..)) && args(obj, ..);
  1441. before(Type obj): allTypeMethods(obj) {
  1442. if (obj == null) throw new RuntimeException();
  1443. }
  1444. }
  1445. aspect CountEntry {
  1446. pointcut allTypeMethods(Type obj): call(* *(..)) && args(obj, ..);
  1447. static int count = 0;
  1448. before(): allTypeMethods(Type) {
  1449. count++;
  1450. }
  1451. }
  1452. ....
  1453. ==== Various cycles
  1454. It is an error for any aspect to be matched by more than one TypePattern
  1455. in a single decare precedence, so:
  1456. [source, java]
  1457. ....
  1458. declare precedence: A, B, A ; // error
  1459. ....
  1460. However, multiple declare precedence forms may legally have this kind of
  1461. circularity. For example, each of these declare precedence is perfectly
  1462. legal:
  1463. [source, java]
  1464. ....
  1465. declare precedence: B, A;
  1466. declare precedence: A, B;
  1467. ....
  1468. And a system in which both constraints are active may also be legal, so
  1469. long as advice from `A` and `B` don't share a join point. So this is an
  1470. idiom that can be used to enforce that `A` and `B` are strongly independent.
  1471. ==== Applies to concrete aspects
  1472. Consider the following library aspects:
  1473. [source, java]
  1474. ....
  1475. abstract aspect Logging {
  1476. abstract pointcut logged();
  1477. before(): logged() {
  1478. System.err.println("thisJoinPoint: " + thisJoinPoint);
  1479. }
  1480. }
  1481. abstract aspect MyProfiling {
  1482. abstract pointcut profiled();
  1483. Object around(): profiled() {
  1484. long beforeTime = System.currentTimeMillis();
  1485. try {
  1486. return proceed();
  1487. } finally {
  1488. long afterTime = System.currentTimeMillis();
  1489. addToProfile(thisJoinPointStaticPart, afterTime - beforeTime);
  1490. }
  1491. }
  1492. abstract void addToProfile(
  1493. org.aspectj.JoinPoint.StaticPart jp,
  1494. long elapsed
  1495. );
  1496. }
  1497. ....
  1498. In order to use either aspect, they must be extended with concrete
  1499. aspects, say, MyLogging and MyProfiling. Because advice only applies
  1500. from concrete aspects, the declare precedence form only matters when
  1501. declaring precedence with concrete aspects. So
  1502. [source, java]
  1503. ....
  1504. declare precedence: Logging, Profiling;
  1505. ....
  1506. has no effect, but both
  1507. [source, java]
  1508. ....
  1509. declare precedence: MyLogging, MyProfiling;
  1510. declare precedence: Logging+, Profiling+;
  1511. ....
  1512. are meaningful.
  1513. === Statically determinable pointcuts
  1514. Pointcuts that appear inside of `declare` forms have certain
  1515. restrictions. Like other pointcuts, these pick out join points, but they
  1516. do so in a way that is statically determinable.
  1517. Consequently, such pointcuts may not include, directly or indirectly
  1518. (through user-defined pointcut declarations) pointcuts that discriminate
  1519. based on dynamic (runtime) context. Therefore, such pointcuts may not be
  1520. defined in terms of
  1521. * `cflow`
  1522. * `cflowbelow`
  1523. * `this`
  1524. * `target`
  1525. * `args`
  1526. * `if`
  1527. all of which can discriminate on runtime information.
  1528. [[semantics-aspects]]
  1529. == Aspects
  1530. An aspect is a crosscutting type defined by the `aspect` declaration.
  1531. === Aspect Declaration
  1532. The `aspect` declaration is similar to the `class` declaration in that
  1533. it defines a type and an implementation for that type. It differs in a
  1534. number of ways:
  1535. ==== Aspect implementation can cut across other types
  1536. In addition to normal Java class declarations such as methods and
  1537. fields, aspect declarations can include AspectJ declarations such as
  1538. advice, pointcuts, and inter-type declarations. Thus, aspects contain
  1539. implementation declarations that can can cut across other types
  1540. (including those defined by other aspect declarations).
  1541. ==== Aspects are not directly instantiated
  1542. Aspects are not directly instantiated with a new expression, with
  1543. cloning, or with serialization. Aspects may have one constructor
  1544. definition, but if so it must be of a constructor taking no arguments
  1545. and throwing no checked exceptions.
  1546. ==== Nested aspects must be `static`
  1547. Aspects may be defined either at the package level, or as a `static`
  1548. nested aspect -- that is, a `static` member of a class, interface, or
  1549. aspect. If it is not at the package level, the aspect _must_ be defined
  1550. with the `static` keyword. Local and anonymous aspects are not allowed.
  1551. === Aspect Extension
  1552. To support abstraction and composition of crosscutting concerns, aspects
  1553. can be extended in much the same way that classes can. Aspect extension
  1554. adds some new rules, though.
  1555. ==== Aspects may extend classes and implement interfaces
  1556. An aspect, abstract or concrete, may extend a class and may implement a
  1557. set of interfaces. Extending a class does not provide the ability to
  1558. instantiate the aspect with a new expression: The aspect may still only
  1559. define a null constructor.
  1560. ==== Classes may not extend aspects
  1561. It is an error for a class to extend or implement an aspect.
  1562. ==== Aspects extending aspects
  1563. Aspects may extend other aspects, in which case not only are fields and
  1564. methods inherited but so are pointcuts. However, aspects may only extend
  1565. abstract aspects. It is an error for a concrete aspect to extend another
  1566. concrete aspect.
  1567. === Aspect instantiation
  1568. Unlike class expressions, aspects are not instantiated with `new`
  1569. expressions. Rather, aspect instances are automatically created to cut
  1570. across programs. A program can get a reference to an aspect instance
  1571. using the static method `aspectOf(..)`.
  1572. Because advice only runs in the context of an aspect instance, aspect
  1573. instantiation indirectly controls when advice runs.
  1574. The criteria used to determine how an aspect is instantiated is
  1575. inherited from its parent aspect. If the aspect has no parent aspect,
  1576. then by default the aspect is a singleton aspect. How an aspect is
  1577. instantiated controls the form of the `aspectOf(..)` method defined on
  1578. the concrete aspect class.
  1579. ==== Singleton Aspects
  1580. * `aspect Id { ... }`
  1581. * `aspect Id issingleton() { ... }`
  1582. By default (or by using the modifier `issingleton()`) an aspect has
  1583. exactly one instance that cuts across the entire program. That instance
  1584. is available at any time during program execution from the static method
  1585. `aspectOf()` automatically defined on all concrete aspects -- so, in the
  1586. above examples, `A.aspectOf()` will return ``A``'s instance. This aspect
  1587. instance is created as the aspect's classfile is loaded.
  1588. Because the an instance of the aspect exists at all join points in the
  1589. running of a program (once its class is loaded), its advice will have a
  1590. chance to run at all such join points.
  1591. (In actuality, one instance of the aspect `A` is made for each version of
  1592. the aspect `A`, so there will be one instantiation for each time `A` is
  1593. loaded by a different classloader.)
  1594. ==== Per-object aspects
  1595. * `aspect Id perthis( Pointcut ) { ... }`
  1596. * `aspect Id pertarget( Pointcut ) { ... }`
  1597. If an aspect `A` is defined `perthis(Pointcut)`, then one object of type `A`
  1598. is created for every object that is the executing object (i.e., `this`)
  1599. at any of the join points picked out by `Pointcut`. The advice defined
  1600. in `A` will run only at a join point where the currently executing object
  1601. has been associated with an instance of `A`.
  1602. Similarly, if an aspect `A` is defined `pertarget(Pointcut)`, then one
  1603. object of type `A` is created for every object that is the target object
  1604. of the join points picked out by `Pointcut`. The advice defined in `A`
  1605. will run only at a join point where the target object has been
  1606. associated with an instance of `A`.
  1607. In either case, the static method call `A.aspectOf(Object)` can be used
  1608. to get the aspect instance (of type `A`) registered with the object. Each
  1609. aspect instance is created as early as possible, but not before reaching
  1610. a join point picked out by `Pointcut` where there is no associated
  1611. aspect of type `A`.
  1612. Both `perthis` and `pertarget` aspects may be affected by code the
  1613. AspectJ compiler controls, as discussed in the xref:implementation.adoc#implementation[Implementation Notes]
  1614. appendix.
  1615. ==== Per-control-flow aspects
  1616. * `aspect Id percflow( Pointcut ) { ... }`
  1617. * `aspect Id percflowbelow( Pointcut ) { ... }`
  1618. If an aspect `A` is defined `percflow(Pointcut)` or
  1619. `percflowbelow(Pointcut)`, then one object of type `A` is created for each
  1620. flow of control of the join points picked out by `Pointcut`, either as
  1621. the flow of control is entered, or below the flow of control,
  1622. respectively. The advice defined in `A` may run at any join point in or
  1623. under that control flow. During each such flow of control, the static
  1624. method `A.aspectOf()` will return an object of type `A`. An instance of
  1625. the aspect is created upon entry into each such control flow.
  1626. ==== Aspect instantiation and advice
  1627. All advice runs in the context of an aspect instance, but it is possible
  1628. to write a piece of advice with a pointcut that picks out a join point
  1629. that must occur before asopect instantiation. For example:
  1630. [source, java]
  1631. ....
  1632. public class Client
  1633. {
  1634. public static void main(String[] args) {
  1635. Client c = new Client();
  1636. }
  1637. }
  1638. aspect Watchcall {
  1639. pointcut myConstructor(): execution(new(..));
  1640. before(): myConstructor() {
  1641. System.err.println("Entering Constructor");
  1642. }
  1643. }
  1644. ....
  1645. The before advice should run before the execution of all constructors in
  1646. the system. It must run in the context of an instance of the Watchcall
  1647. aspect. The only way to get such an instance is to have Watchcall's
  1648. default constructor execute. But before that executes, we need to run
  1649. the before advice...
  1650. There is no general way to detect these kinds of circularities at
  1651. compile time. If advice runs before its aspect is instantiated, AspectJ
  1652. will throw a
  1653. xref:../runtime-api/org/aspectj/lang/NoAspectBoundException.html[`org.aspectj.lang.NoAspectBoundException`].
  1654. === Aspect privilege
  1655. * `privileged aspect Id { ... }`
  1656. Code written in aspects is subject to the same access control rules as
  1657. Java code when referring to members of classes or aspects. So, for
  1658. example, code written in an aspect may not refer to members with default
  1659. (package-protected) visibility unless the aspect is defined in the same
  1660. package.
  1661. While these restrictions are suitable for many aspects, there may be
  1662. some aspects in which advice or inter-type members needs to access
  1663. private or protected resources of other types. To allow this, aspects
  1664. may be declared `privileged`. Code in priviliged aspects has access to
  1665. all members, even private ones.
  1666. [source, java]
  1667. ....
  1668. class C {
  1669. private int i = 0;
  1670. void incI(int x) { i = i+x; }
  1671. }
  1672. privileged aspect A {
  1673. static final int MAX = 1000;
  1674. before(int x, C c): call(void C.incI(int)) && target(c) && args(x) {
  1675. if (c.i+x > MAX) throw new RuntimeException();
  1676. }
  1677. }
  1678. ....
  1679. In this case, if `A` had not been declared `privileged`, the field reference
  1680. `c.i` would have resulted in an error signaled by the compiler.
  1681. If a privileged aspect can access multiple versions of a particular
  1682. member, then those that it could see if it were not privileged take
  1683. precedence. For example, in the code
  1684. [source, java]
  1685. ....
  1686. class C {
  1687. private int i = 0;
  1688. void foo() { }
  1689. }
  1690. privileged aspect A {
  1691. private int C.i = 999;
  1692. before(C c): call(void C.foo()) target(c) {
  1693. System.out.println(c.i);
  1694. }
  1695. }
  1696. ....
  1697. ``A``'s private inter-type field `C.i`, initially bound to 999, will be
  1698. referenced in the body of the advice in preference to ``C``'s privately
  1699. declared field, since `A` would have access to its own inter-type
  1700. fields even if it were not privileged.
  1701. Note that a privileged aspect can access private inter-type declarations
  1702. made by other aspects, since they are simply considered private members
  1703. of that other aspect.