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.adoc 27KB

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