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.

ataspectj.xml 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. <chapter id="ataspectj" xreflabel="AtAspectJ">
  2. <title>An Annotation Based Development Style</title>
  3. <sect1 id="ataspectj-intro">
  4. <title>Introduction</title>
  5. <para>In addition to the familiar AspectJ code-based style of aspect
  6. declaration, AspectJ 5 also supports an annotation-based style of
  7. aspect declaration. We informally call the set of annotations that
  8. support this development style the "@AspectJ" annotations.</para>
  9. <para>
  10. AspectJ 5 allows aspects and their members to be specified using
  11. either the code style or the annotation style. Whichever style you
  12. use, the AspectJ weaver ensures that your program has exactly the
  13. same semantics. It is, to quote a famous advertising campaign,
  14. "a choice, not a compromise". The two styles can be mixed within
  15. a single application, and even within a single source file, though
  16. we doubt this latter mix will be recommended in practice.
  17. </para>
  18. <para>
  19. The use of the @AspectJ annotations means that there are large
  20. classes of AspectJ applications that can be compiled by a regular
  21. Java 5 compiler, and subsequently woven by the AspectJ weaver (for
  22. example, as an additional build stage, or as late as class load-time).
  23. In this chapter we introduce the @AspectJ annotations and show how
  24. they can be used to declare aspects and aspect members.
  25. </para>
  26. </sect1>
  27. <sect1 id="ataspectj-aspects">
  28. <title>Aspect Declarations</title>
  29. <para>
  30. Aspect declarations are supported by the
  31. <literal>org.aspectj.lang.annotation.Aspect</literal>
  32. annotation.
  33. The declaration:
  34. </para>
  35. <programlisting><![CDATA[
  36. @Aspect
  37. public class Foo {}
  38. ]]></programlisting>
  39. <para>Is equivalent to:</para>
  40. <programlisting><![CDATA[
  41. public aspect Foo {}
  42. ]]></programlisting>
  43. <para>To specify an aspect an aspect instantiation model (the default is
  44. singleton), provide the perclause as the
  45. <literal>@Aspect</literal>
  46. value.
  47. For example:
  48. </para>
  49. <programlisting><![CDATA[
  50. @Aspect("perthis(execution(* abc..*(..)))")
  51. public class Foo {}
  52. ]]></programlisting>
  53. <para>is equivalent to...</para>
  54. <programlisting><![CDATA[
  55. public aspect Foo perthis(execution(* abc..*(..))) {}
  56. ]]></programlisting>
  57. <sect2 id="limitations" xreflabel="limitations">
  58. <title>Limitations</title>
  59. <para>Privileged aspects are not supported by the annotation style.</para>
  60. <!--
  61. <programlisting><![CDATA[
  62. @Aspect(isPrivileged=true)
  63. public class Foo {}
  64. ]]></programlisting>
  65. <para>is equivalent to...</para>
  66. <programlisting><![CDATA[
  67. public privileged aspect Foo {}
  68. ]]></programlisting>
  69. -->
  70. </sect2>
  71. </sect1>
  72. <sect1 id="ataspectj-pcadvice">
  73. <title>Pointcuts and Advice</title>
  74. <para>
  75. Pointcut and advice declarations can be made using the
  76. <literal>Pointcut, Before, After, AfterReturning, AfterThrowing,</literal>
  77. and
  78. <literal>Around</literal>
  79. annotations.
  80. </para>
  81. <sect2 id="pointcuts" xreflabel="pointcuts">
  82. <title>Pointcuts</title>
  83. <para>
  84. Pointcuts are specified using the
  85. <literal>org.aspectj.lang.annotation.Pointcut</literal>
  86. annotation
  87. on a method declaration. The method should have a
  88. <literal>void</literal>
  89. return type. The parameters of the method correspond to the parameters
  90. of the pointcut. The modifiers of the method correspond to the modifiers
  91. of the pointcut.
  92. </para>
  93. <para>
  94. As a general rule, the
  95. <literal>@Pointcut</literal>
  96. annotated method must have an empty method body
  97. and must not have any
  98. <literal>throws</literal>
  99. clause. If formal are bound (using
  100. <literal>args(), target(), this(), @args(), @target(), @this(), @annotation())</literal>
  101. in the
  102. pointcut, then they must appear in the method signature.
  103. </para>
  104. <para>
  105. The
  106. <literal>if()</literal>
  107. pointcut is treated specially and is discussed in a later section.
  108. </para>
  109. <para>Here is a simple example of a pointcut declaration in both code and @AspectJ styles:</para>
  110. <programlisting><![CDATA[
  111. @Pointcut("call(* *.*(..))")
  112. void anyCall() {}
  113. ]]></programlisting>
  114. <para>is equivalent to...</para>
  115. <programlisting><![CDATA[
  116. pointcut anyCall() : call(* *.*(..));
  117. ]]></programlisting>
  118. <para>When binding arguments, simply declare the arguments as normal in the annotated method:</para>
  119. <programlisting><![CDATA[
  120. @Pointcut("call(* *.*(int)) && args(i) && target(callee)")
  121. void anyCall(int i, Foo callee) {}
  122. ]]></programlisting>
  123. <para>is equivalent to...</para>
  124. <programlisting><![CDATA[
  125. pointcut anyCall(int i, Foo callee) : call(* *.*(int)) && args(i) && target(callee);
  126. ]]></programlisting>
  127. <para>An example with modifiers (Remember that Java 5 annotations are not
  128. inherited, so the <literal>@Pointcut</literal> annotation must be
  129. present on the extending aspect's pointcut declaration too):</para>
  130. <programlisting><![CDATA[
  131. @Pointcut("")
  132. protected abstract void anyCall();
  133. ]]></programlisting>
  134. <para>is equivalent to...</para>
  135. <programlisting><![CDATA[
  136. protected abstract pointcut anyCall();
  137. ]]></programlisting>
  138. <sect3>
  139. <title>Type references inside @AspectJ annotations</title>
  140. <para>
  141. Using the code style, types referenced in pointcut expressions are
  142. resolved with respect to the imported types in the compilation unit.
  143. When using the annotation style, types referenced in pointcut
  144. expressions are resolved in the absence of any imports and so have
  145. to be fully qualified if they are not by default visible to the
  146. declaring type (outside of the declaring package and
  147. <literal>java.lang</literal>
  148. ). This
  149. does not apply to type patterns with wildcards, which are always resolved
  150. in a global scope.
  151. </para>
  152. <para>
  153. Consider the following compilation unit:
  154. </para>
  155. <programlisting><![CDATA[
  156. package org.aspectprogrammer.examples;
  157. import java.util.List;
  158. public aspect Foo {
  159. pointcut listOperation() : call(* List.*(..));
  160. pointcut anyUtilityCall() : call(* java.util..*(..));
  161. }
  162. ]]></programlisting>
  163. <para>
  164. Using the annotation style this would be written as:
  165. </para>
  166. <programlisting><![CDATA[
  167. package org.aspectprogrammer.examples;
  168. import java.util.List; // redundant but harmless
  169. @Aspect
  170. public class Foo {
  171. @Pointcut("call(* java.util.List.*(..))") // must qualify
  172. void listOperation() {}
  173. @Pointcut("call(* java.util..*(..))")
  174. void anyUtilityCall() {}
  175. }
  176. ]]></programlisting>
  177. </sect3>
  178. <sect3>
  179. <title>if() pointcut expressions</title>
  180. <para>In code style, it is possible to use the
  181. <literal>if(...)</literal>
  182. poincut to define
  183. a conditional pointcut expression which will be evaluated at runtime for each candidate join point.
  184. The
  185. <literal>if(...)</literal>
  186. body can be any valid Java boolean expression, and can use any exposed formal, as well as the join
  187. point forms
  188. <literal>thisJoinPoint, thisJoinPointStaticPart and thisJoinPointEnclosingStaticPart</literal>
  189. .
  190. </para>
  191. <para>
  192. When using the annotation style, it is not possible to write a full Java expression
  193. within
  194. the annotation value so the syntax differs slightly, whilst providing the very same
  195. semantics and runtime behaviour. An
  196. <literal>if()</literal>
  197. pointcut expression can be
  198. declared in an
  199. <literal>@Pointcut</literal>
  200. , but must have either an empty body (<literal>if()</literal>, or be one
  201. of the expression forms
  202. <literal>if(true)</literal>
  203. or
  204. <literal>if(false)</literal>
  205. . The annotated
  206. method must be public, static, and return a boolean. The body of the method contains the
  207. condition to be evaluated. For example:
  208. </para>
  209. <programlisting><![CDATA[
  210. @Pointcut("call(* *.*(int)) && args(i) && if()")
  211. public static boolean someCallWithIfTest(int i) {
  212. return i > 0;
  213. }
  214. ]]></programlisting>
  215. <para>is equivalent to...</para>
  216. <programlisting><![CDATA[
  217. pointcut someCallWithIfTest(int i) : call(* *.*(int)) && args(i) && if(i > 0);
  218. ]]></programlisting>
  219. <para>and the following is also a valid form:</para>
  220. <programlisting><![CDATA[
  221. static int COUNT = 0;
  222. @Pointcut("call(* *.*(int)) && args(i) && if()")
  223. public static boolean someCallWithIfTest(int i, JoinPoint jp, JoinPoint.EnclosingStaticPart esjp) {
  224. // any legal Java expression...
  225. return i > 0
  226. && jp.getSignature().getName.startsWith("doo")
  227. && esjp.getSignature().getName().startsWith("test")
  228. && COUNT++ < 10;
  229. }
  230. @Before("someCallWithIfTest(anInt, jp, enc)")
  231. public void beforeAdviceWithRuntimeTest(int anInt, JoinPoint jp, JoinPoint.EnclosingStaticPart enc) {
  232. //...
  233. }
  234. // Note that the following is NOT valid
  235. /*
  236. @Before("call(* *.*(int)) && args(i) && if()")
  237. public void advice(int i) {
  238. // so you were writing an advice or an if body ?
  239. }
  240. */
  241. ]]></programlisting>
  242. <para>
  243. It is thus possible with the annotation style to use the
  244. <literal>if()</literal>
  245. pointcut
  246. only within an
  247. <literal>@Pointcut</literal>
  248. expression. The
  249. <literal>if()</literal>
  250. must not contain any
  251. body. The annotated
  252. <literal>@Pointcut</literal>
  253. method must then be of the form
  254. <literal>public static boolean</literal>
  255. and can use formal bindings as usual.
  256. Extra
  257. <emphasis>implicit</emphasis>
  258. arguments of type JoinPoint, JoinPoint.StaticPart and JoinPoint.EnclosingStaticPart can also be used
  259. (this is not permitted for regular annotated pointcuts not using the
  260. <literal>if()</literal>
  261. form).
  262. </para>
  263. <para>
  264. The special forms
  265. <literal>if(true)</literal>
  266. and
  267. <literal>if(false)</literal>
  268. can be used in a more
  269. general way and don't imply that the pointcut method must have a body.
  270. You can thus write
  271. <literal>@Before("somePoincut() &amp;&amp; if(false)")</literal>
  272. .
  273. </para>
  274. </sect3>
  275. </sect2>
  276. <sect2 id="advice" xreflabel="advice">
  277. <title>Advice</title>
  278. <para>In this section we first discuss the use of annotations for
  279. simple advice declarations. Then we show how
  280. <literal>thisJoinPoint</literal>
  281. and its siblings are handled in the body of advice and discuss the
  282. treatment of
  283. <literal>proceed</literal>
  284. in around advice.
  285. </para>
  286. <para>Using the annotation style, an advice declaration is written as
  287. a regular Java method with one of the
  288. <literal>Before, After, AfterReturning,
  289. AfterThrowing,</literal>
  290. or
  291. <literal>Around</literal>
  292. annotations. Except in
  293. the case of around advice, the method should return void. The method should
  294. be declared public.
  295. </para>
  296. <para>A method that has an advice annotation is treated exactly as an
  297. advice declaration by AspectJ's weaver. This includes the join points that
  298. arise when the advice is executed (an adviceexecution join point, not a
  299. method execution join point).</para>
  300. <para>The following example shows a simple before advice declaration in
  301. both styles:</para>
  302. <programlisting><![CDATA[
  303. @Before("call(* org.aspectprogrammer..*(..)) && this(Foo)")
  304. public void callFromFoo() {
  305. System.out.println("Call from Foo");
  306. }
  307. ]]></programlisting>
  308. <para>is equivalent to...</para>
  309. <programlisting><![CDATA[
  310. before() : call(* org.aspectprogrammer..*(..)) && this(Foo) {
  311. System.out.println("Call from Foo");
  312. }
  313. ]]></programlisting>
  314. <!--
  315. AMC: enhanced adviceexecution pointcuts and @AdviceName will most likely not make AJ5 1.5.0
  316. <para>Notice one slight difference between the two advice declarations: in
  317. the annotation style, the advice has a name, "callFromFoo". Even though
  318. advice cannot be invoked explicitly, this name is useful in join point
  319. matching when advising advice execution. For this reason, and to preserve
  320. exact semantic equivalence between the two styles, we also support the
  321. <literal>org.aspectj.lang.annotation.AdviceName</literal> annotation.
  322. The exact equivalent declarations are:
  323. </para>
  324. <programlisting><![CDATA[
  325. @AdviceName("callFromFoo")
  326. before() : call(* org.aspectprogrammer..*(..)) && this(Foo) {
  327. System.out.println("Call from Foo");
  328. }
  329. is equivalent to...
  330. @Before("call(* org.aspectprogrammer..*(..)) && this(Foo)")
  331. public void callFromFoo() {
  332. System.out.println("Call from Foo");
  333. }
  334. ]]></programlisting>
  335. -->
  336. <para>If the advice body needs to know which particular
  337. <literal>Foo</literal>
  338. instance
  339. is making the call, just add a parameter to the advice declaration.
  340. </para>
  341. <programlisting><![CDATA[
  342. before(Foo foo) : call(* org.aspectprogrammer..*(..)) && this(foo) {
  343. System.out.println("Call from Foo: " + foo);
  344. }
  345. ]]></programlisting>
  346. <para>can be written as:</para>
  347. <programlisting><![CDATA[
  348. @Before("call(* org.aspectprogrammer..*(..)) && this(foo)")
  349. public void callFromFoo(Foo foo) {
  350. System.out.println("Call from Foo: " + foo);
  351. }
  352. ]]></programlisting>
  353. <para>If the advice body needs access to
  354. <literal>thisJoinPoint</literal>
  355. ,
  356. <literal>thisJoinPointStaticPart</literal>
  357. ,
  358. <literal>thisEnclosingJoinPointStaticPart</literal>
  359. then these need to
  360. be declared as additional method parameters when using the annotation
  361. style.
  362. </para>
  363. <programlisting><![CDATA[
  364. @Before("call(* org.aspectprogrammer..*(..)) && this(foo)")
  365. public void callFromFoo(JoinPoint thisJoinPoint, Foo foo) {
  366. System.out.println("Call from Foo: " + foo + " at "
  367. + thisJoinPoint);
  368. }
  369. ]]></programlisting>
  370. <para>is equivalent to...</para>
  371. <programlisting><![CDATA[
  372. before(Foo foo) : call(* org.aspectprogrammer..*(..)) && this(foo) {
  373. System.out.println("Call from Foo: " + foo + " at "
  374. + thisJoinPoint);
  375. }
  376. ]]></programlisting>
  377. <para>Advice that needs all three variables would be declared:</para>
  378. <programlisting><![CDATA[
  379. @Before("call(* org.aspectprogrammer..*(..)) && this(Foo)")
  380. public void callFromFoo(JoinPoint thisJoinPoint,
  381. JoinPoint.StaticPart thisJoinPointStaticPart,
  382. JoinPoint.EnclosingStaticPart thisEnclosingJoinPointStaticPart) {
  383. // ...
  384. }
  385. ]]></programlisting>
  386. <para>
  387. <literal>JoinPoint.EnclosingStaticPart</literal>
  388. is a new (empty) sub-interface
  389. of
  390. <literal>JoinPoint.StaticPart</literal>
  391. which allows the AspectJ weaver to
  392. distinguish based on type which of
  393. <literal>thisJoinPointStaticPart</literal>
  394. and
  395. <literal>thisEnclosingJoinPointStaticPart</literal>
  396. should be passed in a given
  397. parameter position.
  398. </para>
  399. <para>
  400. <literal>After</literal>
  401. advice declarations take exactly the same form
  402. as
  403. <literal>Before</literal>
  404. , as do the forms of
  405. <literal>AfterReturning</literal>
  406. and
  407. <literal>AfterThrowing</literal>
  408. that do not expose the return type or
  409. thrown exception respectively.
  410. </para>
  411. <para>
  412. To expose a return value with after returning advice simply declare the returning
  413. parameter as a parameter in the method body and bind it with the "returning"
  414. attribute:
  415. </para>
  416. <programlisting><![CDATA[
  417. @AfterReturning("criticalOperation()")
  418. public void phew() {
  419. System.out.println("phew");
  420. }
  421. @AfterReturning(pointcut="call(Foo+.new(..))",returning="f")
  422. public void itsAFoo(Foo f) {
  423. System.out.println("It's a Foo: " + f);
  424. }
  425. ]]></programlisting>
  426. <para>is equivalent to...</para>
  427. <programlisting><![CDATA[
  428. after() returning : criticalOperation() {
  429. System.out.println("phew");
  430. }
  431. after() returning(Foo f) : call(Foo+.new(..)) {
  432. System.out.println("It's a Foo: " + f);
  433. }
  434. ]]></programlisting>
  435. <para>(Note the use of the "pointcut=" prefix in front of the pointcut
  436. expression in the returning case).</para>
  437. <para>After throwing advice works in a similar fashion, using the
  438. <literal>throwing</literal>
  439. attribute when needing to expose a
  440. thrown exception.
  441. </para>
  442. <para>For around advice, we have to tackle the problem of
  443. <literal>proceed</literal>
  444. .
  445. One of the design goals for the annotation style is that a large class of
  446. AspectJ applications should be compilable with a standard Java 5 compiler.
  447. A straight call to
  448. <literal>proceed</literal>
  449. inside a method body:
  450. </para>
  451. <programlisting><![CDATA[
  452. @Around("call(* org.aspectprogrammer..*(..))")
  453. public Object doNothing() {
  454. return proceed(); // CE on this line
  455. }
  456. ]]></programlisting>
  457. <para>will result in a "No such method" compilation error. For this
  458. reason AspectJ 5 defines a new sub-interface of
  459. <literal>JoinPoint</literal>
  460. ,
  461. <literal>ProceedingJoinPoint</literal>
  462. .
  463. </para>
  464. <programlisting><![CDATA[
  465. public interface ProceedingJoinPoint extends JoinPoint {
  466. public Object proceed(Object[] args);
  467. }
  468. ]]></programlisting>
  469. <para>The around advice given above can now be written as:</para>
  470. <programlisting><![CDATA[
  471. @Around("call(* org.aspectprogrammer..*(..))")
  472. public Object doNothing(ProceedingJoinPoint thisJoinPoint) {
  473. return thisJoinPoint.proceed();
  474. }
  475. ]]></programlisting>
  476. <para>Here's an example that uses parameters for the proceed call:</para>
  477. <programlisting><![CDATA[
  478. @Aspect
  479. public class ProceedAspect {
  480. @Pointcut("call(* setAge(..)) && args(i)")
  481. void setAge(int i) {}
  482. @Around("setAge(i)")
  483. public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint, int i) {
  484. return thisJoinPoint.proceed(new Object[]{i*2}); //using Java 5 autoboxing
  485. }
  486. }
  487. ]]></programlisting>
  488. <para>is equivalent to:</para>
  489. <programlisting><![CDATA[
  490. public aspect ProceedAspect {
  491. pointcut setAge(int i): call(* setAge(..)) && args(i);
  492. Object around(int i): setAge(i) {
  493. return proceed(i*2);
  494. }
  495. }
  496. ]]></programlisting>
  497. <para>Note that the ProceedingJoinPoint does not need to be passed to the proceed(..) arguments.
  498. </para>
  499. <para>In code style, the proceed method has the same signature as the advice, any reordering of
  500. actual arguments to the joinpoint that is done in the advice signature must be respected. Annotation
  501. style is different. The proceed(..) call takes, in this order:
  502. <itemizedlist>
  503. <listitem>If 'this()' was used in the pointcut <emphasis>for binding</emphasis>, it must be passed first in proceed(..).
  504. </listitem>
  505. <listitem>If 'target()' was used in the pointcut <emphasis>for binding</emphasis>, it must be passed next in proceed(..) - it will be the
  506. first argument to proceed(..) if this() was not used for binding.
  507. </listitem>
  508. <listitem>Finally come <emphasis>all</emphasis> the arguments expected at the join point, in the order they
  509. are supplied at the join point. Effectively the advice signature is ignored - it doesn't
  510. matter if a subset of arguments were bound or the ordering was changed in the advice
  511. signature, the proceed(..) calls takes all of them in the right order for the join point.
  512. </listitem>
  513. </itemizedlist>
  514. </para>
  515. <para>Since proceed(..) in this case takes an Object array, AspectJ cannot do as much compile time
  516. checking as it can for code style. If the rules above aren't obeyed then it will unfortunately
  517. manifest as a runtime error.
  518. </para>
  519. </sect2>
  520. </sect1>
  521. <sect1 id="ataspectj-itds">
  522. <title>Inter-type Declarations</title>
  523. <para>
  524. Inter-type declarations are challenging to support using an annotation style. For code style aspects
  525. compiled with the ajc compiler, the entire type system can be made aware of inter-type declarations (new
  526. supertypes, new methods, new fields) and the completeness and correctness of it can be guaranteed.
  527. Achieving this with an annotation style is hard because the source code may simply be compiled with javac
  528. where the type system cannot be influenced and what is compiled must be 'pure java'.
  529. </para>
  530. <para>
  531. AspectJ 1.5.0 introduced @DeclareParents, an attempt to offer something like that which is achievable with
  532. code style declare parents and the other intertype declarations (fields, methods, constructors). However,
  533. it has proved too challenging to get close to the expressiveness and capabilities of code style in this area
  534. and effectively @DeclareParents is offering just a mixin strategy. The definition of mixin I am using here is that when
  535. some interface I is mixed into some target type T then this means that all the methods from I are created in T and their
  536. implementations are simple forwarding methods that call a delegate which that provides an implementation of I.
  537. </para>
  538. <para>
  539. The next section covers @DeclareParents but AspectJ 1.6.4 introduces @DeclareMixin - an improved approach to defining
  540. a mixin and the choice of a different name for the annotation will hopefully alleviate some of the confusion about
  541. why @DeclareParents just doesn't offer the same semantics as the code style variant. Offering @DeclareMixin also gives
  542. code style developers a new tool for a simple mixin whereas previously they would have avoided @DeclareParents
  543. thinking what it could only do was already achievable with code style syntax.
  544. </para>
  545. <para>
  546. The defaultImpl attribute of @DeclareParents may become deprecated if @DeclareMixin proves popular, leaving
  547. @DeclareParents purely as a way to introduce a marker interface.
  548. </para>
  549. <sect2 id="atDeclareParents" xreflabel="atDeclareParents">
  550. <title>@DeclareParents</title>
  551. <para>
  552. Consider the following aspect:
  553. </para>
  554. <programlisting><![CDATA[
  555. public aspect MoodIndicator {
  556. public interface Moody {};
  557. private Mood Moody.mood = Mood.HAPPY;
  558. public Mood Moody.getMood() {
  559. return mood;
  560. }
  561. declare parents : org.xyz..* implements Moody;
  562. before(Moody m) : execution(* *.*(..)) && this(m) {
  563. System.out.println("I'm feeling " + m.getMood());
  564. }
  565. }
  566. ]]></programlisting>
  567. <para>
  568. This declares an interface
  569. <literal>Moody</literal>
  570. , and then makes two
  571. inter-type declarations on the interface - a field that is private to the
  572. aspect, and a method that returns the mood. Within the body of the inter-type
  573. declared method
  574. <literal>getMoody</literal>
  575. , the type of
  576. <literal>this</literal>
  577. is
  578. <literal>Moody</literal>
  579. (the target type of the inter-type declaration).
  580. </para>
  581. <para>Using the annotation style this aspect can be written:
  582. </para>
  583. <programlisting><![CDATA[
  584. @Aspect
  585. public class MoodIndicator {
  586. // this interface can be outside of the aspect
  587. public interface Moody {
  588. Mood getMood();
  589. };
  590. // this implementation can be outside of the aspect
  591. public static class MoodyImpl implements Moody {
  592. private Mood mood = Mood.HAPPY;
  593. public Mood getMood() {
  594. return mood;
  595. }
  596. }
  597. // the field type must be the introduced interface. It can't be a class.
  598. @DeclareParents(value="org.xzy..*",defaultImpl=MoodyImpl.class)
  599. private Moody implementedInterface;
  600. @Before("execution(* *.*(..)) && this(m)")
  601. void feelingMoody(Moody m) {
  602. System.out.println("I'm feeling " + m.getMood());
  603. }
  604. }
  605. ]]></programlisting>
  606. <para>
  607. This is very similar to the mixin mechanism supported by AspectWerkz. The
  608. effect of the
  609. <literal>@DeclareParents</literal>
  610. annotation is equivalent to
  611. a declare parents statement that all types matching the type pattern implement
  612. the given interface (in this case Moody).
  613. Each method declared in the interface is treated as an inter-type declaration.
  614. Note how this scheme operates within the constraints
  615. of Java type checking and ensures that
  616. <literal>this</literal>
  617. has access
  618. to the exact same set of members as in the code style example.
  619. </para>
  620. <para>
  621. Note that it is illegal to use the @DeclareParents annotation on an aspect' field of a non-interface type.
  622. The interface type is the inter-type declaration contract that dictates
  623. which methods are declared on the target type.
  624. </para>
  625. <programlisting><![CDATA[
  626. // this type will be affected by the inter-type declaration as the type pattern matches
  627. package org.xyz;
  628. public class MoodTest {
  629. public void test() {
  630. // see here the cast to the introduced interface (required)
  631. Mood mood = ((Moody)this).getMood();
  632. ...
  633. }
  634. }
  635. ]]></programlisting>
  636. <para>The <literal>@DeclareParents</literal> annotation can also be used without specifying
  637. a <literal>defaultImpl</literal> value (for example,
  638. <literal>@DeclareParents("org.xyz..*")</literal>). This is equivalent to a
  639. <literal>declare parents ... implements</literal> clause, and does <emphasis>not</emphasis>
  640. make any inter-type declarations for default implementation of the interface methods.
  641. </para>
  642. <para>
  643. Consider the following aspect:
  644. </para>
  645. <programlisting><![CDATA[
  646. public aspect SerializableMarker {
  647. declare parents : org.xyz..* implements Serializable;
  648. }
  649. ]]></programlisting>
  650. <para>Using the annotation style this aspect can be written:
  651. </para>
  652. <programlisting><![CDATA[
  653. @Aspect
  654. public class SerializableMarker {
  655. @DeclareParents("org.xyz..*")
  656. Serializable implementedInterface;
  657. }
  658. ]]></programlisting>
  659. <para>
  660. If the interface defines one or more operations, and these are not implemented by
  661. the target type, an error will be issued during weaving.
  662. </para>
  663. </sect2>
  664. <sect2 id="atDeclareMixin" xreflabel="atDeclareMixin">
  665. <title>@DeclareMixin</title>
  666. <para>
  667. Consider the following aspect:
  668. </para>
  669. <programlisting><![CDATA[
  670. public aspect MoodIndicator {
  671. public interface Moody {};
  672. private Mood Moody.mood = Mood.HAPPY;
  673. public Mood Moody.getMood() {
  674. return mood;
  675. }
  676. declare parents : org.xyz..* implements Moody;
  677. before(Moody m) : execution(* *.*(..)) && this(m) {
  678. System.out.println("I'm feeling " + m.getMood());
  679. }
  680. }
  681. ]]></programlisting>
  682. <para>
  683. This declares an interface <literal>Moody</literal>, and then makes two inter-type declarations on the interface
  684. - a field that is private to the aspect, and a method that returns the mood. Within the body of the inter-type
  685. declared method <literal>getMoody</literal>, the type of <literal>this</literal> is <literal>Moody</literal>
  686. (the target type of the inter-type declaration).
  687. </para>
  688. <para>Using the annotation style this aspect can be written:
  689. </para>
  690. <programlisting><![CDATA[
  691. @Aspect
  692. public class MoodIndicator {
  693. // this interface can be outside of the aspect
  694. public interface Moody {
  695. Mood getMood();
  696. };
  697. // this implementation can be outside of the aspect
  698. public static class MoodyImpl implements Moody {
  699. private Mood mood = Mood.HAPPY;
  700. public Mood getMood() {
  701. return mood;
  702. }
  703. }
  704. // The DeclareMixin annotation is attached to a factory method that can return instances of the delegate
  705. // which offers an implementation of the mixin interface. The interface that is mixed in is the
  706. // return type of the method.
  707. @DeclareMixin("org.xyz..*")
  708. public static Moody createMoodyImplementation() {
  709. return new MoodyImpl();
  710. }
  711. @Before("execution(* *.*(..)) && this(m)")
  712. void feelingMoody(Moody m) {
  713. System.out.println("I'm feeling " + m.getMood());
  714. }
  715. }
  716. ]]></programlisting>
  717. <para>
  718. Basically, the <literal>@DeclareMixin</literal> annotation is attached to a factory method. The
  719. factory method specifies the interface to mixin as its return type, and calling the method should
  720. create an instance of a delegate that implements the interface. This is the interface which will
  721. be delegated to from any target matching the specified type pattern.
  722. </para>
  723. <para>
  724. Exploiting this syntax requires the user to obey the rules of pure Java. So references to any
  725. targeted type as if it were affected by the Mixin must be made through a cast, like this:
  726. </para>
  727. <programlisting><![CDATA[
  728. // this type will be affected by the inter-type declaration as the type pattern matches
  729. package org.xyz;
  730. public class MoodTest {
  731. public void test() {
  732. // see here the cast to the introduced interface (required)
  733. Mood mood = ((Moody)this).getMood();
  734. ...
  735. }
  736. }
  737. ]]></programlisting>
  738. <para>
  739. Sometimes the delegate instance may want to perform differently depending upon the type/instance for
  740. which it is behaving as a delegate. To support this it is possible for the factory method to specify a
  741. parameter. If it does, then when the factory method is called the parameter will be the object instance for
  742. which a delegate should be created:
  743. </para>
  744. <programlisting><![CDATA[
  745. @Aspect
  746. public class Foo {
  747. @DeclareMixin("org.xyz..*")
  748. public static SomeInterface createDelegate(Object instance) {
  749. return new SomeImplementation(instance);
  750. }
  751. }
  752. ]]></programlisting>
  753. <para>
  754. It is also possible to make the factory method non-static - and in this case it can then exploit
  755. the local state in the surrounding aspect instance, but this is only supported for singleton aspects:
  756. </para>
  757. <programlisting><![CDATA[
  758. @Aspect
  759. public class Foo {
  760. public int maxLimit=35;
  761. @DeclareMixin("org.xyz..*")
  762. public SomeInterface createDelegate(Object instance) {
  763. return new SomeImplementation(instance,maxLimit);
  764. }
  765. }
  766. ]]></programlisting>
  767. <para>
  768. Although the interface type is usually determined purely from the return type of the factory method, it can
  769. be specified in the annotation if necessary. In this example the return type of the method extends multiple
  770. other interfaces and only a couple of them (I and J) should be mixed into any matching targets:
  771. </para>
  772. <programlisting><![CDATA[
  773. // interfaces is an array of interface classes that should be mixed in
  774. @DeclareMixin(value="org.xyz..*",interfaces={I.class,J.class})
  775. public static InterfaceExtendingLotsOfInterfaces createMoodyImplementation() {
  776. return new MoodyImpl();
  777. }
  778. ]]></programlisting>
  779. <para>
  780. There are clearly similarities between <literal>@DeclareMixin</literal> and <literal>@DeclareParents</literal> but
  781. <literal>@DeclareMixin</literal> is not pretending to offer more than a simple mixin strategy. The flexibility in
  782. being able to provide the factory method instead of requiring a no-arg constructor for the implementation also
  783. enables delegate instances to make decisions based upon the type for which they are the delegate.
  784. </para>
  785. <para>
  786. Any annotations defined on the interface methods are also put upon the delegate forwarding methods created in the
  787. matched target type.
  788. </para>
  789. </sect2>
  790. </sect1>
  791. <sect1 id="ataspectj-declare">
  792. <title>Declare statements</title>
  793. <para>The previous section on inter-type declarations covered the case
  794. of declare parents ... implements. The 1.5.0 release of AspectJ 5 does
  795. not support annotation style declarations for declare parents ... extends
  796. and declare soft (programs with these declarations would not in general
  797. be compilable by a regular Java 5 compiler, reducing the priority of
  798. their implementation). These may be supported in a future release.</para>
  799. <para>
  800. Declare annotation is also not supported in the 1.5.0 release of AspectJ 5.
  801. </para>
  802. <para>Declare precedence <emphasis>is</emphasis>
  803. supported. For declare precedence, use the
  804. <literal>@DeclarePrecedence</literal>
  805. annotation as in the following example:
  806. </para>
  807. <programlisting><![CDATA[
  808. public aspect SystemArchitecture {
  809. declare precedence : Security*, TransactionSupport, Persistence;
  810. // ...
  811. }
  812. can be written as:
  813. @Aspect
  814. @DeclarePrecedence("Security*,org.xyz.TransactionSupport,org.xyz.Persistence")
  815. public class SystemArchitecture {
  816. // ...
  817. }
  818. ]]></programlisting>
  819. <!--
  820. note: below is not supported for now.
  821. <para>
  822. Declare annotation is supported via annotations on a dummy type member. If the
  823. <literal>Target</literal>
  824. specification of the annotation allows it, use a field,
  825. otherwise declare a member of the type required by the
  826. <literal>Target</literal>
  827. .
  828. For example:
  829. </para>
  830. <programlisting><![CDATA[
  831. public aspect DeclareAnnotationExamples {
  832. declare annotation : org.xyz.model..* : @BusinessDomain;
  833. declare annotation : public * BankAccount+.*(..) : @Secured(role="supervisor");
  834. declare anotation : * DAO+.* : @Persisted;
  835. }
  836. can be written as...
  837. @Aspect
  838. public class DeclareAnnotationExamples {
  839. @DeclareAnnotation("org.xyz.model..*)
  840. @BusinessDomain Object modelClass;
  841. // this example assumes that the @Secured annotation has a Target
  842. // annotation with value ElementType.METHOD
  843. @DeclareAnnotation("public * org.xyz.banking.BankAccount+.*(..)")
  844. @Secured(role="supervisor) void bankAccountMethod();
  845. @DeclareAnnotation("* DAO+.*")
  846. @Persisted Object daoFields;
  847. }
  848. ]]></programlisting>
  849. <para>
  850. <emphasis>Note: Declare annotation is not available in AspectJ 1.5 M3 and syntax may change
  851. when the design and implementation is complete.</emphasis>
  852. </para>
  853. -->
  854. <para>We also support annotation style declarations for declare warning and
  855. declare error - any corresponding warnings and errors will be emitted at
  856. weave time, not when the aspects containing the declarations are compiled.
  857. (This is the same behaviour as when using declare warning or error with the
  858. code style). Declare warning and error declarations are made by annotating
  859. a string constant whose value is the message to be issued.</para>
  860. <para>Note that the String must be a literal and not the result of the invocation
  861. of a static method for example.</para>
  862. <programlisting><![CDATA[
  863. declare warning : call(* javax.sql..*(..)) && !within(org.xyz.daos..*)
  864. : "Only DAOs should be calling JDBC.";
  865. declare error : execution(* IFoo+.*(..)) && !within(org.foo..*)
  866. : "Only foo types can implement IFoo";
  867. can be written as...
  868. @DeclareWarning("call(* javax.sql..*(..)) && !within(org.xyz.daos..*)")
  869. static final String aMessage = "Only DAOs should be calling JDBC.";
  870. @DeclareError("execution(* IFoo+.*(..)) && !within(org.foo..*)")
  871. static final String badIFooImplementors = "Only foo types can implement IFoo";
  872. // the following is not valid since the message is not a String literal
  873. @DeclareError("execution(* IFoo+.*(..)) && !within(org.foo..*)")
  874. static final String badIFooImplementorsCorrupted = getMessage();
  875. static String getMessage() {
  876. return "Only foo types can implement IFoo " + System.currentTimeMillis();
  877. }
  878. ]]></programlisting>
  879. </sect1>
  880. <sect1 id="ataspectj-aspectof">
  881. <title>aspectOf() and hasAspect() methods</title>
  882. <para>A central part of AspectJ's programming model is that aspects
  883. written using the code style and compiled using ajc support
  884. <literal>aspectOf</literal>
  885. and
  886. <literal>hasAspect</literal>
  887. static
  888. methods. When developing an aspect using the annotation style and compiling
  889. using a regular Java 5 compiler, these methods will not be visible to the
  890. compiler and will result in a compilation error if another part of the
  891. program tries to call them.
  892. </para>
  893. <para>To provide equivalent support for AspectJ applications compiled with
  894. a standard Java 5 compiler, AspectJ 5 defines the
  895. <literal>Aspects</literal>
  896. utility class:
  897. </para>
  898. <programlisting><![CDATA[
  899. public class Aspects {
  900. /* variation used for singleton, percflow, percflowbelow */
  901. static<T> public static T aspectOf(T aspectType) {...}
  902. /* variation used for perthis, pertarget */
  903. static<T> public static T aspectOf(T aspectType, Object forObject) {...}
  904. /* variation used for pertypewithin */
  905. static<T> public static T aspectOf(T aspectType, Class forType) {...}
  906. /* variation used for singleton, percflow, percflowbelow */
  907. public static boolean hasAspect(Object anAspect) {...}
  908. /* variation used for perthis, pertarget */
  909. public static boolean hasAspect(Object anAspect, Object forObject) {...}
  910. /* variation used for pertypewithin */
  911. public static boolean hasAspect(Object anAspect, Class forType) {...}
  912. }
  913. ]]></programlisting>
  914. <!-- TODO AV - stuff below is not done -->
  915. <!--
  916. <para>When the AspectJ weaver sees calls to these methods, it will convert
  917. them into the most efficient form possible (to get performance equivalent
  918. to a direct <literal>MyAspect.aspectOf()</literal> call).</para>
  919. -->
  920. </sect1>
  921. </chapter>