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.

generics.adoc 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. = Generics
  2. [[generics-inJava5]]
  3. == Generics in Java 5
  4. This section provides the essential information about generics in Java 5
  5. needed to understand how generics are treated in AspectJ 5. For a full
  6. introduction to generics in Java, please see the documentation for the
  7. Java 5 SDK.
  8. === Declaring Generic Types
  9. A generic type is declared with one or more type parameters following
  10. the type name. By convention formal type parameters are named using a
  11. single letter, though this is not required. A simple generic list type
  12. (that can contain elements of any type `E`) could be declared:
  13. [source, java]
  14. ....
  15. interface List<E> {
  16. Iterator<E> iterator();
  17. void add(E anItem);
  18. E remove(E anItem);
  19. }
  20. ....
  21. It is important to understand that unlike template mechanisms there will
  22. only be one type, and one class file, corresponding to the `List`
  23. interface, regardless of how many different instantiations of the `List`
  24. interface a program has (each potentially providing a different value
  25. for the type parameter `E`). A consequence of this is that you cannot
  26. refer to the type parameters of a type declaration in a static method or
  27. initializer, or in the declaration or initializer of a static variable.
  28. A _parameterized type_ is an invocation of a generic type with concrete
  29. values supplied for all of its type parameters (for example,
  30. `List<String>` or `List<Food>`).
  31. A generic type may be declared with multiple type parameters. In
  32. addition to simple type parameter names, type parameter declarations can
  33. also constrain the set of types allowed by using the `extends` keyword.
  34. Some examples follow:
  35. `class Foo<T> {...}`::
  36. A class `Foo` with one type parameter, `T`.
  37. `class Foo<T,S> {...}`::
  38. A class `Foo` with two type parameters, `T` and `S`.
  39. `class Foo<T extends Number> {...}`::
  40. A class `Foo` with one type parameter `T`, where `T` must be
  41. instantiated as the type `Number` or a subtype of `Number`.
  42. `class Foo<T, S extends T> {...}`::
  43. A class `Foo` with two type parameters, `T` and `S`. `Foo` must be
  44. instantiated with a type `S` that is a subtype of the type specified
  45. for parameter `T`.
  46. `class Foo<T extends Number & Comparable> {...}`::
  47. A class `Foo` with one type parameter, `T`. `Foo` must be instantiated
  48. with a type that is a subtype of `Number` and that implements
  49. `Comparable`.
  50. === Using Generic and Parameterized Types
  51. You declare a variable (or a method/constructor argument) of a
  52. parameterized type by specifying a concrete type specfication for each
  53. type parameter in the generic type. The following example declares a
  54. list of strings and a list of numbers:
  55. [source, java]
  56. ....
  57. List<String> strings;
  58. List<Number> numbers;
  59. ....
  60. It is also possible to declare a variable of a generic type without
  61. specifying any values for the type parameters (a _raw_ type). For
  62. example, `List strings`. In this case, unchecked warnings may be issued
  63. by the compiler when the referenced object is passed as a parameter to a
  64. method expecting a parameterized type such as a `List<String>`. New code
  65. written in the Java 5 language would not be expected to use raw types.
  66. Parameterized types are instantiated by specifying type parameter values
  67. in the constructor call expression as in the following examples:
  68. [source, java]
  69. ....
  70. List<String> strings = new MyListImpl<String>();
  71. List<Number> numbers = new MyListImpl<Number>();
  72. ....
  73. When declaring parameterized types, the `?` wildcard may be used, which
  74. stands for "some type". The `extends` and `super` keywords may be used
  75. in conjunction with the wildcard to provide upper and lower bounds on
  76. the types that may satisfy the type constraints. For example:
  77. `List<?>`::
  78. A list containing elements of some type, the type of the elements in
  79. the list is unknown.
  80. `List<? extends Number>`::
  81. A list containing elements of some type that extends Number, the exact
  82. type of the elements in the list is unknown.
  83. `List<? super Double>`::
  84. A list containing elements of some type that is a super-type of
  85. Double, the exact type of the elements in the list is unknown.
  86. A generic type may be extended as any other type. Given a generic type
  87. `Foo<T>` then a subtype `Goo` may be declared in one of the following
  88. ways:
  89. `class Goo extends Foo`::
  90. Here `Foo` is used as a raw type, and the appropriate warning messages
  91. will be issued by the compiler on attempting to invoke methods in
  92. `Foo`.
  93. `class Goo<E> extends Foo`::
  94. `Goo` is a generic type, but the super-type `Foo` is used as a raw
  95. type and the appropriate warning messages will be issued by the
  96. compiler on attempting to invoke methods defined by `Foo`.
  97. `class Goo<E> extends Foo<E>`::
  98. This is the most usual form. `Goo` is a generic type with one
  99. parameter that extends the generic type `Foo` with that same
  100. parameter. So `Goo<String<` is a subclass of `Foo<String>`.
  101. `class Goo<E,F> extends Foo<E>`::
  102. `Goo` is a generic type with two parameters that extends the generic
  103. type `Foo` with the first type parameter of `Goo` being used to
  104. parameterize `Foo`. So `Goo<String,Integer<` is a subclass of
  105. `Foo<String>`.
  106. `class Goo extends Foo<String>`::
  107. `Goo` is a type that extends the parameterized type `Foo<String>`.
  108. A generic type may implement one or more generic interfaces, following
  109. the type binding rules given above. A type may also implement one or
  110. more parameterized interfaces (for example,
  111. `class X implements List<String>`, however a type may not at the same
  112. time be a subtype of two interface types which are different
  113. parameterizations of the same interface.
  114. === Subtypes, Supertypes, and Assignability
  115. The supertype of a generic type `C` is the type given in the extends
  116. clause of `C`, or `Object` if no extends clause is present. Given the
  117. type declaration
  118. [source, java]
  119. ....
  120. public interface List<E> extends Collection<E> {... }
  121. ....
  122. then the supertype of `List<E>` is `Collection<E>`.
  123. The supertype of a parameterized type `P` is the type given in the
  124. extends clause of `P`, or `Object` if no extends clause is present. Any
  125. type parameters in the supertype are substituted in accordance with the
  126. parameterization of `P`. An example will make this much clearer: Given
  127. the type `List<Double>` and the definition of the `List` given above,
  128. the direct supertype is `Collection<Double>`. `List<Double>` is _not_
  129. considered to be a subtype of `List<Number>`.
  130. An instance of a parameterized type `P<T1,T2,...Tn>`may be assigned to a
  131. variable of the same type or a supertype without casting. In addition it
  132. may be assigned to a variable `R<S1,S2,...Sm>` where `R` is a supertype
  133. of `P` (the supertype relationship is reflexive), `m <= n`, and for all
  134. type parameters `S1..m`, `Tm` equals `Sm` _or_ `Sm` is a wildcard type
  135. specification and `Tm` falls within the bounds of the wildcard. For
  136. example, `List<String>` can be assigned to a variable of type
  137. `Collection<?>`, and `List<Double>` can be assigned to a variable of
  138. type `List<? extends Number>`.
  139. === Generic Methods and Constructors
  140. A static method may be declared with one or more type parameters as in
  141. the following declaration:
  142. [source, java]
  143. ....
  144. static <T> T first(List<T> ts) { ... }
  145. ....
  146. Such a definition can appear in any type, the type parameter `T` does
  147. not need to be declared as a type parameter of the enclosing type.
  148. Non-static methods may also be declared with one or more type parameters
  149. in a similar fashion:
  150. [source, java]
  151. ....
  152. <T extends Number> T max(T t1, T t2) { ... }
  153. ....
  154. The same technique can be used to declare a generic constructor.
  155. === Erasure
  156. Generics in Java are implemented using a technique called _erasure_. All
  157. type parameter information is erased from the run-time type system.
  158. Asking an object of a parameterized type for its class will return the
  159. class object for the raw type (eg. `List` for an object declared to be
  160. of type `List<String>`. A consequence of this is that you cannot at
  161. runtime ask if an object is an `instanceof` a parameterized type.
  162. [[generics-inAspectJ5]]
  163. == Generics in AspectJ 5
  164. AspectJ 5 provides full support for all of the Java 5 language features,
  165. including generics. Any legal Java 5 program is a legal AspectJ 5
  166. progam. In addition, AspectJ 5 provides support for generic and
  167. parameterized types in pointcuts, inter-type declarations, and declare
  168. statements. Parameterized types may freely be used within aspect
  169. members, and support is also provided for generic _abstract_ aspects.
  170. === Matching generic and parameterized types in pointcut expressions
  171. The simplest way to work with generic and parameterized types in
  172. pointcut expressions and type patterns is simply to use the raw type
  173. name. For example, the type pattern `List` will match the generic type
  174. `List<E>` and any parameterization of that type
  175. (`List<String>, List<?>, List<? extends Number>` and so on. This ensures
  176. that pointcuts written in existing code that is not generics-aware will
  177. continue to work as expected in AspectJ 5. It is also the recommended
  178. way to match against generic and parameterized types in AspectJ 5 unless
  179. you explicitly wish to narrow matches to certain parameterizations of a
  180. generic type.
  181. Generic methods and constructors, and members defined in generic types,
  182. may use type variables as part of their signature. For example:
  183. [source, java]
  184. ....
  185. public class Utils {
  186. /** static generic method */
  187. static <T> T first(List<T> ts) { ... }
  188. /** instance generic method */
  189. <T extends Number> T max(T t1, T t2) { ... }
  190. }
  191. public class G<T> {
  192. // field with parameterized type
  193. T myData;
  194. // method with parameterized return type
  195. public List<T> getAllDataItems() {...}
  196. }
  197. ....
  198. AspectJ 5 does not allow the use of type variables in pointcut
  199. expressions and type patterns. Instead, members that use type parameters
  200. as part of their signature are matched by their _erasure_. Java 5
  201. defines the rules for determing the erasure of a type as follows.
  202. Let `|T|` represent the erasure of some type `T`. Then:
  203. * The erasure of a parameterized type `T<T1,...,Tn>` is `|T|`.
  204. For example, the erasure of `List<String>` is `List`.
  205. * The erasure of a nested type `T.C` is `|T|.C`.
  206. For example, the erasure of the nested type `Foo<T>.Bar` is `Foo.Bar`.
  207. * The erasure of an array type `T[]` is `|T|[]`.
  208. For example, the erasure of `List<String>[]` is `List[]`.
  209. * The erasure of a type variable is its leftmost bound.
  210. For example, the erasure of a type variable `P` is `Object`,
  211. and the erasure of a type variable `N extends Number` is `Number`.
  212. * The erasure of every other type is the type itself.
  213. Applying these rules to the earlier examples, we find that the methods
  214. defined in `Utils` can be matched by a signature pattern matching
  215. `static Object Utils.first(List)` and `Number Utils.max(Number, Number)`
  216. respectively. The members of the generic type `G` can be matched by a
  217. signature pattern matching `Object G.myData` and
  218. `public List G.getAllDataItems()` respectively.
  219. ==== Restricting matching using parameterized types
  220. Pointcut matching can be further restricted to match only given
  221. parameterizations of parameter types (methods and constructors), return
  222. types (methods) and field types (fields). This is achieved by specifying
  223. a parameterized type pattern at the appropriate point in the signature
  224. pattern. For example, given the class `Foo`:
  225. [source, java]
  226. ....
  227. public class Foo {
  228. List<String> myStrings;
  229. List<Float> myFloats;
  230. public List<String> getStrings() { return myStrings; }
  231. public List<Float> getFloats() { return myFloats; }
  232. public void addStrings(List<String> evenMoreStrings) {
  233. myStrings.addAll(evenMoreStrings);
  234. }
  235. }
  236. ....
  237. Then a `get` join point for the field `myStrings` can be matched by the
  238. pointcut `get(List Foo.myStrings)` and by the pointcut
  239. `get(List<String> Foo.myStrings)`, but _not_ by the pointcut
  240. `get(List<Number> *)`.
  241. A `get` join point for the field `myFloats` can be matched by the
  242. pointcut `get(List Foo.myFloats)`, the pointcut `get(List<Float> *)`,
  243. and the pointcut `get(List<Number+> *)`. This last example shows how
  244. AspectJ type patterns can be used to match type parameters types just
  245. like any other type. The pointcut `get(List<Double> *)` does _not_
  246. match.
  247. The execution of the methods `getStrings` and `getFloats` can be matched
  248. by the pointcut expression `execution(List get*(..))`, and the pointcut
  249. expression `execution(List<*> get*(..))`, but only `getStrings` is
  250. matched by `execution(List<String> get*(..))` and only `getFloats` is
  251. matched by `execution(List<Number+> get*(..))`
  252. A call to the method `addStrings` can be matched by the pointcut
  253. expression `call(* addStrings(List))` and by the expression
  254. `call(* addStrings(List<String>))`, but _not_ by the expression
  255. `call(* addStrings(List<Number>))`.
  256. Remember that any type variable reference in a generic member is
  257. _always_ matched by its erasure. Thus given the following example:
  258. [source, java]
  259. ....
  260. class G<T> {
  261. List<T> foo(List<String> ls) { return null; }
  262. }
  263. ....
  264. The execution of `foo` can be matched by `execution(List foo(List))`,
  265. `execution(List foo(List<String>>))`, and
  266. `execution(* foo(List<String<))`but _not_ by
  267. `execution(List<Object> foo(List<String>>)` since the erasure of
  268. `List<T>` is `List` and not `List<Object>`.
  269. ==== Generic wildcards and signature matching
  270. When it comes to signature matching, a type parameterized using a
  271. generic wildcard is a distinct type. For example, `List<?>` is a very
  272. different type to `List<String>`, even though a variable of type
  273. `List<String>` can be assigned to a variable of type `List<?>`. Given
  274. the methods:
  275. [source, java]
  276. ....
  277. class C {
  278. public void foo(List<? extends Number> listOfSomeNumberType) {}
  279. public void bar(List<?> listOfSomeType) {}
  280. public void goo(List<Double> listOfDoubles) {}
  281. }
  282. ....
  283. `execution(* C.*(List))`::
  284. Matches an execution join point for any of the three methods.
  285. `execution(* C.*(List<? extends Number>))`::
  286. matches only the execution of `foo`, and _not_ the execution of `goo`
  287. since `List<? extends Number>` and `List<Double>` are distinct types.
  288. `execution(* C.*(List<?>))`::
  289. matches only the execution of `bar`.
  290. `execution(* C.*(List<? extends Object+>))`::
  291. matches both the execution of `foo` and the execution of `bar` since
  292. the upper bound of `List<?>` is implicitly `Object`.
  293. ==== Treatment of bridge methods
  294. Under certain circumstances a Java 5 compiler is required to create
  295. _bridge methods_ that support the compilation of programs using raw
  296. types. Consider the types
  297. [source, java]
  298. ....
  299. class Generic<T> {
  300. public T foo(T someObject) {
  301. return someObject;
  302. }
  303. }
  304. class SubGeneric<N extends Number> extends Generic<N> {
  305. public N foo(N someNumber) {
  306. return someNumber;
  307. }
  308. }
  309. ....
  310. The class `SubGeneric` extends `Generic` and overrides the method `foo`.
  311. Since the upper bound of the type variable `N` in `SubGeneric` is
  312. different to the upper bound of the type variable `T` in `Generic`, the
  313. method `foo` in `SubGeneric` has a different erasure to the method `foo`
  314. in `Generic`. This is an example of a case where a Java 5 compiler will
  315. create a _bridge method_ in `SubGeneric`. Although you never see it, the
  316. bridge method will look something like this:
  317. [source, java]
  318. ....
  319. public Object foo(Object arg) {
  320. Number n = (Number) arg; // "bridge" to the signature defined in this type
  321. return foo(n);
  322. }
  323. ....
  324. Bridge methods are synthetic artefacts generated as a result of a
  325. particular compilation strategy and have no execution join points in
  326. AspectJ 5. So the pointcut `execution(Object SubGeneric.foo(Object))`
  327. does not match anything. (The pointcut
  328. `execution(Object Generic.foo(Object))` matches the execution of `foo`
  329. in both `Generic` and `SubGeneric` since both are implementations of
  330. `Generic.foo`).
  331. It _is_ possible to _call_ a bridge method as the following short code
  332. snippet demonstrates. Such a call _does_ result in a call join point for
  333. the call to the method.
  334. [source, java]
  335. ....
  336. SubGeneric rawType = new SubGeneric();
  337. rawType.foo("hi"); // call to bridge method (will result in a runtime failure in this case)
  338. Object n = new Integer(5);
  339. rawType.foo(n); // call to bridge method that would succeed at runtime
  340. ....
  341. ==== Runtime type matching with this(), target() and args()
  342. The `this()`, `target()`, and `args()` pointcut expressions all match
  343. based on the runtime type of their arguments. Because Java 5 implements
  344. generics using erasure, it is not possible to ask at runtime whether an
  345. object is an instance of a given parameterization of a type (only
  346. whether or not it is an instance of the erasure of that parameterized
  347. type). Therefore AspectJ 5 does not support the use of parameterized
  348. types with the `this()` and `target()` pointcuts. Parameterized types
  349. may however be used in conjunction with `args()`. Consider the following
  350. class
  351. [source, java]
  352. ....
  353. public class C {
  354. public void foo(List<String> listOfStrings) {}
  355. public void bar(List<Double> listOfDoubles) {}
  356. public void goo(List<? extends Number> listOfSomeNumberType) {}
  357. }
  358. ....
  359. `args(List)`::
  360. will match an execution or call join point for any of these methods
  361. `args(List<String>)`::
  362. will match an execution or call join point for `foo`.
  363. `args(List<Double>)`::
  364. matches an execution or call join point for `bar`, and _may_ match at
  365. an execution or call join point for `goo` since it is legitimate to
  366. pass an object of type `List<Double>` to a method expecting a
  367. `List<? extends Number>`.
  368. +
  369. In this situation, a runtime test would normally be applied to
  370. ascertain whether or not the argument was indeed an instance of the
  371. required type. However, in the case of parameterized types such a test
  372. is not possible and therefore AspectJ 5 considers this a match, but
  373. issues an _unchecked_ warning. For example, compiling the aspect `A`
  374. below with the class `C` produces the compilation warning: `unchecked
  375. match of List<Double> with List<? extends Number> when argument is an
  376. instance of List at join point method-execution(void C.goo(List<?
  377. extends Number>)) [Xlint:uncheckedArgument]`;
  378. [source, java]
  379. ....
  380. public aspect A {
  381. before(List<Double> listOfDoubles) : execution(* C.*(..)) && args(listOfDoubles) {
  382. for (Double d : listOfDoubles) {
  383. // do something
  384. }
  385. }
  386. }
  387. ....
  388. Like all Lint messages, the `uncheckedArgument` warning can be
  389. configured in severity from the default warning level to error or even
  390. ignore if preferred. In addition, AspectJ 5 offers the annotation
  391. `@SuppressAjWarnings` which is the AspectJ equivalent of Java's
  392. `@SuppressWarnings` annotation. If the advice is annotated with
  393. `@SuppressWarnings` then _all_ lint warnings issued during matching of
  394. pointcut associated with the advice will be suppressed. To suppress just
  395. an `uncheckedArgument` warning, use the annotation
  396. `@SuppressWarnings("uncheckedArgument")` as in the following examples:
  397. [source, java]
  398. ....
  399. import org.aspectj.lang.annotation.SuppressAjWarnings
  400. public aspect A {
  401. @SuppressAjWarnings // will not see *any* lint warnings for this advice
  402. before(List<Double> listOfDoubles) : execution(* C.*(..)) && args(listOfDoubles) {
  403. for (Double d : listOfDoubles) {
  404. // do something
  405. }
  406. }
  407. @SuppressAjWarnings("uncheckedArgument") // will not see *any* lint warnings for this advice
  408. before(List<Double> listOfDoubles) : execution(* C.*(..)) && args(listOfDoubles) {
  409. for (Double d : listOfDoubles) {
  410. // do something
  411. }
  412. }
  413. }
  414. ....
  415. The safest way to deal with `uncheckedArgument` warnings however is to
  416. restrict the pointcut to match only at those join points where the
  417. argument is guaranteed to match. This is achieved by combining `args`
  418. with a `call` or `execution` signature matching pointcut. In the
  419. following example the advice will match the execution of `bar` but not
  420. of `goo` since the signature of `goo` is not matched by the execution
  421. pointcut expression.
  422. [source, java]
  423. ....
  424. public aspect A {
  425. before(List<Double> listOfDoubles) : execution(* C.*(List<Double>)) && args(listOfDoubles) {
  426. for (Double d : listOfDoubles) {
  427. // do something
  428. }
  429. }
  430. }
  431. ....
  432. Generic wildcards can be used in args type patterns, and matching
  433. follows regular Java 5 assignability rules. For example, `args(List<?>)`
  434. will match a list argument of any type, and
  435. `args(List<? extends Number>)` will match an argument of type
  436. `List<Number>, List<Double>, List<Float>` and so on. Where a match
  437. cannot be fully statically determined, the compiler will once more issue
  438. an `uncheckedArgument` warning.
  439. Consider the following program:
  440. [source, java]
  441. ....
  442. public class C {
  443. public static void main(String[] args) {
  444. C c = new C();
  445. List<String> ls = new ArrayList<String>();
  446. List<Double> ld = new ArrayList<Double>();
  447. c.foo("hi");
  448. c.foo(ls);
  449. c.foo(ld);
  450. }
  451. public void foo(Object anObject) {}
  452. }
  453. aspect A {
  454. before(List<? extends Number> aListOfSomeNumberType)
  455. : call(* foo(..)) && args(aListOfSomeNumberType) {
  456. // process list...
  457. }
  458. }
  459. ....
  460. From the signature of `foo` all we know is that the runtime argument
  461. will be an instance of `Object`.Compiling this program gives the
  462. unchecked argument warning: `unchecked match of List<? extends Number>
  463. with List when argument is an instance of List at join point
  464. method-execution(void C.foo(Object)) [Xlint:uncheckedArgument]`. The
  465. advice will not execute at the call join point for `c.foo("hi")` since
  466. `String` is not an instance of `List`. The advice _will_ execute at the
  467. call join points for `c.foo(ls)` and `c.foo(ld)` since in both cases the
  468. argument is an instance of `List`.
  469. Combine a wildcard argument type with a signature pattern to avoid
  470. unchecked argument matches. In the example below we use the signature
  471. pattern `List<Number+>` to match a call to any method taking a
  472. `List<Number>, List<Double>, List<Float>` and so on. In addition the
  473. signature pattern `List<? extends Number+>` can be used to match a call
  474. to a method declared to take a `List<? extends Number>`,
  475. `List<? extends Double>` and so on. Taken together, these restrict
  476. matching to only those join points at which the argument is guaranteed
  477. to be an instance of `List<? extends Number>`.
  478. [source, java]
  479. ....
  480. aspect A {
  481. before(List<? extends Number> aListOfSomeNumberType)
  482. : (call(* foo(List<Number+>)) || call(* foo(List<? extends Number+>)))
  483. && args(aListOfSomeNumberType) {
  484. // process list...
  485. }
  486. }
  487. ....
  488. ==== Binding return values in after returning advice
  489. After returning advice can be used to bind the return value from a
  490. matched join point. AspectJ 5 supports the use of a parameterized type
  491. in the returning clause, with matching following the same rules as
  492. described for args. For example, the following aspect matches the
  493. execution of any method returning a `List`, and makes the returned list
  494. available to the body of the advice.
  495. [source, java]
  496. ....
  497. public aspect A {
  498. pointcut executionOfAnyMethodReturningAList() : execution(List *(..));
  499. after() returning(List<?> listOfSomeType) : executionOfAnyMethodReturningAList() {
  500. for (Object element : listOfSomeType) {
  501. // process element...
  502. }
  503. }
  504. }
  505. ....
  506. The pointcut uses the raw type pattern `List`, and hence it matches
  507. methods returning any kind of list (`List<String>, List<Double>`, and so
  508. on). We've chosen to bind the returned list as the parameterized type
  509. `List<?>` in the advice since Java's type checking will now ensure that
  510. we only perform safe operations on the list.
  511. Given the class
  512. [source, java]
  513. ....
  514. public class C {
  515. public List<String> foo(List<String> listOfStrings) {...}
  516. public List<Double> bar(List<Double> listOfDoubles) {...}
  517. public List<? extends Number> goo(List<? extends Number> listOfSomeNumberType) {...}
  518. }
  519. ....
  520. The advice in the aspect below will run after the execution of `bar` and
  521. bind the return value. It will also run after the execution of `goo` and
  522. bind the return value, but gives an `uncheckedArgument` warning during
  523. compilation. It does _not_ run after the execution of `foo`.
  524. [source, java]
  525. ....
  526. public aspect Returning {
  527. after() returning(List<Double> listOfDoubles) : execution(* C.*(..)) {
  528. for(Double d : listOfDoubles) {
  529. // process double...
  530. }
  531. }
  532. }
  533. ....
  534. As with `args` you can guarantee that after returning advice only
  535. executes on lists _statically determinable_ to be of the right type by
  536. specifying a return type pattern in the associated pointcut. The
  537. `@SuppressAjWarnings` annotation can also be used if desired.
  538. ==== Declaring pointcuts inside generic types
  539. Pointcuts can be declared in both classes and aspects. A pointcut
  540. declared in a generic type may use the type variables of the type in
  541. which it is declared. All references to a pointcut declared in a generic
  542. type from outside of that type must be via a parameterized type
  543. reference, and not a raw type reference.
  544. Consider the generic type `Generic` with a pointcut `foo`:
  545. [source, java]
  546. ....
  547. public class Generic<T> {
  548. /**
  549. * matches the execution of any implementation of a method defined for T
  550. */
  551. public pointcut foo() : execution(* T.*(..));
  552. }
  553. ....
  554. Such a pointcut must be refered to using a parameterized reference as
  555. shown below.
  556. [source, java]
  557. ....
  558. public aspect A {
  559. // runs before the execution of any implementation of a method defined for MyClass
  560. before() : Generic<MyClass>.foo() {
  561. // ...
  562. }
  563. // runs before the execution of any implementation of a method defined for YourClass
  564. before() : Generic<YourClass>.foo() {
  565. // ...
  566. }
  567. // results in a compilation error - raw type reference
  568. before() : Generic.foo() { }
  569. }
  570. ....
  571. === Inter-type Declarations
  572. AspectJ 5 supports the inter-type declaration of generic methods, and of
  573. members on generic types. For generic methods, the syntax is exactly as
  574. for a regular method declaration, with the addition of the target type
  575. specification:
  576. `<T extends Number> T Utils.max(T first, T second) {...}`::
  577. Declares a generic instance method `max` on the class `Util`. The
  578. `max` method takes two arguments, `first` and `second` which must both
  579. be of the same type (and that type must be `Number` or a subtype of
  580. `Number`) and returns an instance of that type.
  581. `static <E> E Utils.first(List<E> elements) {...}`::
  582. Declares a static generic method `first` on the class `Util`. The
  583. `first` method takes a list of elements of some type, and returns an
  584. instance of that type.
  585. <T> Sorter.new(List<T> elements,Comparator<? super T> comparator) `{...}`::
  586. Declares a constructor on the class `Sorter`. The constructor takes a
  587. list of elements of some type, and a comparator that can compare
  588. instances of the element type.
  589. A generic type may be the target of an inter-type declaration, used
  590. either in its raw form or with type parameters specified. If type
  591. parameters are specified, then the number of type parameters given must
  592. match the number of type parameters in the generic type declaration.
  593. Type parameter _names_ do not have to match. For example, given the
  594. generic type `Foo<T,S extends Number>` then:
  595. `String Foo.getName() {...}`::
  596. Declares a `getName` method on behalf of the type `Foo`. It is not
  597. possible to refer to the type parameters of Foo in such a declaration.
  598. `public R Foo<Q, R>.getMagnitude() {...}`::
  599. Declares a method `getMagnitude` on the generic class `Foo`. The
  600. method returns an instance of the type substituted for the second type
  601. parameter in an invocation of `Foo` If `Foo` is declared as
  602. `Foo<T,N extends Number> {...}` then this inter-type declaration is
  603. equivalent to the declaration of a method `public N getMagnitude()`
  604. within the body of `Foo`.
  605. `R Foo<Q, R extends Number>.getMagnitude() {...}`::
  606. Results in a compilation error since a bounds specification is not
  607. allowed in this form of an inter-type declaration (the bounds are
  608. determined from the declaration of the target type).
  609. A parameterized type may not be the target of an inter-type declaration.
  610. This is because there is only one type (the generic type) regardless of
  611. how many different invocations (parameterizations) of that generic type
  612. are made in a program. Therefore it does not make sense to try and
  613. declare a member on behalf of (say) `Bar<String>`, you can only declare
  614. members on the generic type `Bar<T>`.
  615. [[declare-parents-java5]]
  616. === Declare Parents
  617. Both generic and parameterized types can be used as the parent type in a
  618. `declare parents` statement (as long as the resulting type hierarchy
  619. would be well-formed in accordance with Java's sub-typing rules).
  620. Generic types may also be used as the target type of a `declare parents`
  621. statement.
  622. `declare parents: Foo implements List<String>`::
  623. The `Foo` type implements the `List<String>` interface. If `Foo`
  624. already implements some other parameterization of the `List` interface
  625. (for example, `List<Integer>` then a compilation error will result
  626. since a type cannot implement multiple parameterizations of the same
  627. generic interface type.
  628. === Declare Soft
  629. It is an error to use a generic or parameterized type as the softened
  630. exception type in a declare soft statement. Java 5 does not permit a
  631. generic class to be a direct or indirect subtype of `Throwable` (JLS
  632. 8.1.2).
  633. === Generic Aspects
  634. AspectJ 5 allows an _abstract_ aspect to be declared as a generic type.
  635. Any concrete aspect extending a generic abstract aspect must extend a
  636. parameterized version of the abstract aspect. Wildcards are not
  637. permitted in this parameterization.
  638. Given the aspect declaration:
  639. [source, java]
  640. ....
  641. public abstract aspect ParentChildRelationship<P,C> {
  642. // ...
  643. }
  644. ....
  645. then
  646. `public aspect FilesInFolders extends ParentChildRelationship<Folder,File> {...`::
  647. declares a concrete sub-aspect, `FilesInFolders` which extends the
  648. parameterized abstract aspect `ParentChildRelationship<Folder,File>`.
  649. `public aspect FilesInFolders extends ParentChildRelationship {...`::
  650. results in a compilation error since the `ParentChildRelationship`
  651. aspect must be fully parameterized.
  652. `public aspect ThingsInFolders<T> extends ParentChildRelationship<Folder,T>`::
  653. results in a compilation error since concrete aspects may not have
  654. type parameters.
  655. `public abstract aspect ThingsInFolders<T> extends ParentChildRelationship<Folder,T>`::
  656. declares a sub-aspect of `ParentChildRelationship` in which `Folder`
  657. plays the role of parent (is bound to the type variable `P`).
  658. The type parameter variables from a generic aspect declaration may be
  659. used in place of a type within any member of the aspect, _except for
  660. within inter-type declarations_. For example, we can declare a
  661. `ParentChildRelationship` aspect to manage the bi-directional
  662. relationship between parent and child nodes as follows:
  663. [source, java]
  664. ....
  665. /**
  666. * a generic aspect, we've used descriptive role names for the type variables
  667. * (Parent and Child) but you could use anything of course
  668. */
  669. public abstract aspect ParentChildRelationship<Parent,Child> {
  670. /** generic interface implemented by parents */
  671. interface ParentHasChildren<C extends ChildHasParent>{
  672. List<C> getChildren();
  673. void addChild(C child);
  674. void removeChild(C child);
  675. }
  676. /** generic interface implemented by children */
  677. interface ChildHasParent<P extends ParentHasChildren>{
  678. P getParent();
  679. void setParent(P parent);
  680. }
  681. /** ensure the parent type implements ParentHasChildren<child type> */
  682. declare parents: Parent implements ParentHasChildren<Child>;
  683. /** ensure the child type implements ChildHasParent<parent type> */
  684. declare parents: Child implements ChildHasParent<Parent>;
  685. // Inter-type declarations made on the *generic* interface types to provide
  686. // default implementations.
  687. /** list of children maintained by parent */
  688. private List<C> ParentHasChildren<C>.children = new ArrayList<C>();
  689. /** reference to parent maintained by child */
  690. private P ChildHasParent<P>.parent;
  691. /** Default implementation of getChildren for the generic type ParentHasChildren */
  692. public List<C> ParentHasChildren<C>.getChildren() {
  693. return Collections.unmodifiableList(children);
  694. }
  695. /** Default implementation of getParent for the generic type ChildHasParent */
  696. public P ChildHasParent<P>.getParent() {
  697. return parent;
  698. }
  699. /**
  700. * Default implementation of addChild, ensures that parent of child is
  701. * also updated.
  702. */
  703. public void ParentHasChildren<C>.addChild(C child) {
  704. if (child.parent != null) {
  705. child.parent.removeChild(child);
  706. }
  707. children.add(child);
  708. child.parent = this;
  709. }
  710. /**
  711. * Default implementation of removeChild, ensures that parent of
  712. * child is also updated.
  713. */
  714. public void ParentHasChildren<C>.removeChild(C child) {
  715. if (children.remove(child)) {
  716. child.parent = null;
  717. }
  718. }
  719. /**
  720. * Default implementation of setParent for the generic type ChildHasParent.
  721. * Ensures that this child is added to the children of the parent too.
  722. */
  723. public void ChildHasParent<P>.setParent(P parent) {
  724. parent.addChild(this);
  725. }
  726. /**
  727. * Matches at an addChild join point for the parent type P and child type C
  728. */
  729. public pointcut addingChild(Parent p, Child c) :
  730. execution(* ParentHasChildren.addChild(ChildHasParent)) && this(p) && args(c);
  731. /**
  732. * Matches at a removeChild join point for the parent type P and child type C
  733. */
  734. public pointcut removingChild(Parent p, Child c) :
  735. execution(* ParentHasChildren.removeChild(ChildHasParent)) && this(p) && args(c);
  736. }
  737. ....
  738. The example aspect captures the protocol for managing a bi-directional
  739. parent-child relationship between any two types playing the role of
  740. parent and child. In a compiler implementation managing an abstract
  741. syntax tree (AST) in which AST nodes may contain other AST nodes we
  742. could declare the concrete aspect:
  743. [source, java]
  744. ....
  745. public aspect ASTNodeContainment extends ParentChildRelationship<ASTNode,ASTNode> {
  746. before(ASTNode parent, ASTNode child) : addingChild(parent, child) {
  747. // ...
  748. }
  749. }
  750. ....
  751. As a result of this declaration, `ASTNode` gains members:
  752. * `List<ASTNode> children`
  753. * `ASTNode parent`
  754. * `List<ASTNode>getChildren()`
  755. * `ASTNode getParent()`
  756. * `void addChild(ASTNode child)`
  757. * `void removeChild(ASTNode child)`
  758. * `void setParent(ASTNode parent)`
  759. In a system managing orders, we could declare the concrete aspect:
  760. [source, java]
  761. ....
  762. public aspect OrderItemsInOrders extends ParentChildRelationship<Order, OrderItem> {}
  763. ....
  764. As a result of this declaration, `Order` gains members:
  765. * `List<OrderItem> children`
  766. * `List<OrderItem> getChildren()`
  767. * `void addChild(OrderItem child)`
  768. * `void removeChild(OrderItem child)`
  769. and `OrderItem` gains members:
  770. * `Order parent`
  771. * `Order getParent()`
  772. * `void setParent(Order parent)`
  773. A second example of an abstract aspect, this time for handling
  774. exceptions in a uniform manner, is shown below:
  775. [source, java]
  776. ....
  777. abstract aspect ExceptionHandling<T extends Throwable> {
  778. /**
  779. * method to be implemented by sub-aspects to handle thrown exceptions
  780. */
  781. protected abstract void onException(T anException);
  782. /**
  783. * to be defined by sub-aspects to specify the scope of exception handling
  784. */
  785. protected abstract pointcut inExceptionHandlingScope();
  786. /**
  787. * soften T within the scope of the aspect
  788. */
  789. declare soft: T : inExceptionHandlingScope();
  790. /**
  791. * bind an exception thrown in scope and pass it to the handler
  792. */
  793. after() throwing (T anException) : inExceptionHandlingScope() {
  794. onException(anException);
  795. }
  796. }
  797. ....
  798. Notice how the type variable `T extends Throwable` allows the components
  799. of the aspect to be designed to work together in a type-safe manner. The
  800. following concrete sub-aspect shows how the abstract aspect might be
  801. extended to handle `IOExceptions`.
  802. [source, java]
  803. ....
  804. public aspect IOExceptionHandling extends ExceptionHandling<IOException>{
  805. protected pointcut inExceptionHandlingScope() :
  806. call(* doIO*(..)) && within(org.xyz..*);
  807. /**
  808. * called whenever an IOException is thrown in scope.
  809. */
  810. protected void onException(IOException ex) {
  811. System.err.println("handled exception: " + ex.getMessage());
  812. throw new MyDomainException(ex);
  813. }
  814. }
  815. ....