/usr/share/doc/aspectj-doc/progguide/printable.html is in aspectj-doc 1.8.9-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 | <html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>The AspectJTM Programming Guide</title><link rel="stylesheet" type="text/css" href="aspectj-docs.css"><meta name="generator" content="DocBook XSL Stylesheets V1.79.1"><meta name="description" content="This programming guide describes the AspectJ language. A companion guide describes the tools which are part of the AspectJ development environment. If you are completely new to AspectJ, you should first read for a broad overview of programming in AspectJ. If you are already familiar with AspectJ, but want a deeper understanding, you should read and look at the examples in the chapter. If you want a more formal definition of AspectJ, you should read ."></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="book"><div class="titlepage"><div><div><h1 class="title"><a name="idm1"></a>The AspectJ<sup>TM</sup> Programming Guide</h1></div><div><div class="authorgroup"><div class="author"><h3 class="author"><span class="othername">the AspectJ Team</span></h3></div></div></div><div><div class="legalnotice"><a name="idm8"></a><p>
Copyright (c) 1998-2001 Xerox Corporation,
2002-2003 Palo Alto Research Center, Incorporated.
All rights reserved.
</p></div></div><div><div class="abstract"><p class="title"><b>Abstract</b></p><p>
This programming guide describes the AspectJ language. A
companion guide describes the tools which are part of the
AspectJ development environment.
</p><p>
If you are completely new to AspectJ, you should first read
<a class="xref" href="#starting" title="Chapter 1. Getting Started with AspectJ">Getting Started with AspectJ</a> for a broad overview of programming
in AspectJ. If you are already familiar with AspectJ, but want a deeper
understanding, you should read <a class="xref" href="#language" title="Chapter 2. The AspectJ Language">The AspectJ Language</a> and
look at the examples in the chapter. If you want a more formal
definition of AspectJ, you should read <a class="xref" href="#semantics" title="Appendix B. Language Semantics">Semantics</a>.
</p></div></div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="preface"><a href="#preface">Preface</a></span></dt><dt><span class="chapter"><a href="#starting">1. Getting Started with AspectJ</a></span></dt><dd><dl><dt><span class="sect1"><a href="#starting-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#starting-aspectj">Introduction to AspectJ</a></span></dt><dd><dl><dt><span class="sect2"><a href="#the-dynamic-join-point-model">The Dynamic Join Point Model</a></span></dt><dt><span class="sect2"><a href="#pointcuts">Pointcuts</a></span></dt><dt><span class="sect2"><a href="#advice">Advice</a></span></dt><dt><span class="sect2"><a href="#inter-type-declarations">Inter-type declarations</a></span></dt><dt><span class="sect2"><a href="#aspects">Aspects</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-development">Development Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing">Tracing</a></span></dt><dt><span class="sect2"><a href="#profiling-and-logging">Profiling and Logging</a></span></dt><dt><span class="sect2"><a href="#pre-and-post-conditions">Pre- and Post-Conditions</a></span></dt><dt><span class="sect2"><a href="#contract-enforcement">Contract Enforcement</a></span></dt><dt><span class="sect2"><a href="#configuration-management">Configuration Management</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-production">Production Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#change-monitoring">Change Monitoring</a></span></dt><dt><span class="sect2"><a href="#context-passing">Context Passing</a></span></dt><dt><span class="sect2"><a href="#starting-production-consistentBehavior">Providing Consistent Behavior</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-conclusion">Conclusion</a></span></dt></dl></dd><dt><span class="chapter"><a href="#language">2. The AspectJ Language</a></span></dt><dd><dl><dt><span class="sect1"><a href="#language-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#language-anatomy">The Anatomy of an Aspect</a></span></dt><dd><dl><dt><span class="sect2"><a href="#an-example-aspect">An Example Aspect</a></span></dt><dt><span class="sect2"><a href="#pointcuts">Pointcuts</a></span></dt><dt><span class="sect2"><a href="#advice">Advice</a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-joinPoints">Join Points and Pointcuts</a></span></dt><dd><dl><dt><span class="sect2"><a href="#some-example-pointcuts">Some Example Pointcuts</a></span></dt><dt><span class="sect2"><a href="#call-vs-execution">call vs. execution</a></span></dt><dt><span class="sect2"><a href="#pointcut-composition">Pointcut composition</a></span></dt><dt><span class="sect2"><a href="#pointcut-parameters">Pointcut Parameters</a></span></dt><dt><span class="sect2"><a href="#example">Example: <code class="literal">HandleLiveness</code></a></span></dt><dt><span class="sect2"><a href="#pointcut-best-practice">Writing good pointcuts</a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-advice">Advice</a></span></dt><dt><span class="sect1"><a href="#language-interType">Inter-type declarations</a></span></dt><dd><dl><dt><span class="sect2"><a href="#inter-type-scope">Inter-type Scope</a></span></dt><dt><span class="sect2"><a href="#example-pointassertions">Example: <code class="literal">PointAssertions</code></a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-thisJoinPoint">thisJoinPoint</a></span></dt></dl></dd><dt><span class="chapter"><a href="#examples">3. Examples</a></span></dt><dd><dl><dt><span class="sect1"><a href="#examples-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#examples-howto">Obtaining, Compiling and Running the Examples</a></span></dt><dt><span class="sect1"><a href="#examples-basic">Basic Techniques</a></span></dt><dd><dl><dt><span class="sect2"><a href="#examples-joinPoints">Join Points and <code class="literal">thisJoinPoint</code></a></span></dt><dt><span class="sect2"><a href="#examples-roles">Roles and Views</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-development">Development Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing-using-aspects">Tracing using aspects</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-production">Production Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#a-bean-aspect">A Bean Aspect</a></span></dt><dt><span class="sect2"><a href="#the-subject-observer-protocol">The Subject/Observer Protocol</a></span></dt><dt><span class="sect2"><a href="#a-simple-telecom-simulation">A Simple Telecom Simulation</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-reusable">Reusable Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing-using-aspects-revisited">Tracing using Aspects, Revisited</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#idioms">4. Idioms</a></span></dt><dd><dl><dt><span class="sect1"><a href="#idioms-intro">Introduction</a></span></dt></dl></dd><dt><span class="chapter"><a href="#pitfalls">5. Pitfalls</a></span></dt><dd><dl><dt><span class="sect1"><a href="#pitfalls-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#pitfalls-infiniteLoops">Infinite loops</a></span></dt></dl></dd><dt><span class="appendix"><a href="#quick">A. AspectJ Quick Reference</a></span></dt><dd><dl><dt><span class="sect1"><a href="#quick-pointcuts">Pointcuts</a></span></dt><dt><span class="sect1"><a href="#quick-typePatterns">Type Patterns</a></span></dt><dt><span class="sect1"><a href="#quick-advice">Advice</a></span></dt><dt><span class="sect1"><a href="#quick-interType">Inter-type member declarations</a></span></dt><dt><span class="sect1"><a href="#quick-other">Other declarations</a></span></dt><dt><span class="sect1"><a href="#quick-aspectAssociations">Aspects</a></span></dt></dl></dd><dt><span class="appendix"><a href="#semantics">B. Language Semantics</a></span></dt><dd><dl><dt><span class="sect1"><a href="#semantics-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#semantics-joinPoints">Join Points</a></span></dt><dt><span class="sect1"><a href="#semantics-pointcuts">Pointcuts</a></span></dt><dd><dl><dt><span class="sect2"><a href="#pointcut-definition">Pointcut definition</a></span></dt><dt><span class="sect2"><a href="#context-exposure">Context exposure</a></span></dt><dt><span class="sect2"><a href="#primitive-pointcuts">Primitive pointcuts</a></span></dt><dt><span class="sect2"><a href="#signatures">Signatures</a></span></dt><dt><span class="sect2"><a href="#matching">Matching</a></span></dt><dt><span class="sect2"><a href="#type-patterns">Type patterns</a></span></dt><dt><span class="sect2"><a href="#pattern-summary">Pattern Summary</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-advice">Advice</a></span></dt><dd><dl><dt><span class="sect2"><a href="#advice-modifiers">Advice modifiers</a></span></dt><dt><span class="sect2"><a href="#advice-and-checked-exceptions">Advice and checked exceptions</a></span></dt><dt><span class="sect2"><a href="#advice-precedence">Advice precedence</a></span></dt><dt><span class="sect2"><a href="#reflective-access-to-the-join-point">Reflective access to the join point</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-declare">Static crosscutting</a></span></dt><dd><dl><dt><span class="sect2"><a href="#inter-type-member-declarations">Inter-type member declarations</a></span></dt><dt><span class="sect2"><a href="#access-modifiers">Access modifiers</a></span></dt><dt><span class="sect2"><a href="#conflicts">Conflicts</a></span></dt><dt><span class="sect2"><a href="#extension-and-implementation">Extension and Implementation</a></span></dt><dt><span class="sect2"><a href="#interfaces-with-members">Interfaces with members</a></span></dt><dt><span class="sect2"><a href="#warnings-and-errors">Warnings and Errors</a></span></dt><dt><span class="sect2"><a href="#softened-exceptions">Softened exceptions</a></span></dt><dt><span class="sect2"><a href="#advice-precedence">Advice Precedence</a></span></dt><dt><span class="sect2"><a href="#statically-determinable-pointcuts">Statically determinable pointcuts</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-aspects">Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#aspect-declaration">Aspect Declaration</a></span></dt><dt><span class="sect2"><a href="#aspect-extension">Aspect Extension</a></span></dt><dt><span class="sect2"><a href="#aspect-instantiation">Aspect instantiation</a></span></dt><dt><span class="sect2"><a href="#aspect-privilege">Aspect privilege</a></span></dt></dl></dd></dl></dd><dt><span class="appendix"><a href="#implementation">C. Implementation Notes</a></span></dt><dd><dl><dt><span class="sect1"><a href="#idm3245">Compiler Notes</a></span></dt><dt><span class="sect1"><a href="#idm3275">Bytecode Notes</a></span></dt><dd><dl><dt><span class="sect2"><a href="#the-class-expression-and-string">The .class expression and String +</a></span></dt><dt><span class="sect2"><a href="#the-handler-join-point">The Handler join point</a></span></dt><dt><span class="sect2"><a href="#initializers-and-inter-type-constructors">Initializers and Inter-type Constructors</a></span></dt></dl></dd><dt><span class="sect1"><a href="#idm3322">Annotation-style Notes</a></span></dt><dt><span class="sect1"><a href="#idm3325">Summary of implementation requirements</a></span></dt></dl></dd></dl></div><div class="preface"><div class="titlepage"><div><div><h1 class="title"><a name="preface"></a>Preface</h1></div></div></div><p>
This programming guide does three things. It
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem"><p>introduces the AspectJ language</p></li><li class="listitem"><p>
defines each of AspectJ's constructs and their semantics, and
</p></li><li class="listitem"><p>
provides examples of their use.
</p></li></ul></div><p>
It includes appendices that give a reference to the syntax of AspectJ,
a more formal description of AspectJ's semantics, and a description of
notes about the AspectJ implementation.
</p><p>
The first section, <a class="xref" href="#starting" title="Chapter 1. Getting Started with AspectJ">Getting Started with AspectJ</a>, provides a gentle
overview of writing AspectJ programs. It also shows how one can
introduce AspectJ into an existing development effort in stages,
reducing the associated risk. You should read this section if this is
your first exposure to AspectJ and you want to get a sense of what
AspectJ is all about.
</p><p>
The second section, <a class="xref" href="#language" title="Chapter 2. The AspectJ Language">The AspectJ Language</a>, covers the features of
the language in more detail, using code snippets as examples. All the
basics of the language is covered, and after reading this section, you
should be able to use the language correctly.
</p><p>
The next section, <a class="xref" href="#examples" title="Chapter 3. Examples">Examples</a>, comprises a set of
complete programs that not only show the features being used, but also
try to illustrate recommended practice. You should read this section
after you are familiar with the elements of AspectJ.
</p><p>
Finally, there are two short chapters, one on <a class="xref" href="#idioms" title="Chapter 4. Idioms">Idioms</a>
and one on <a class="xref" href="#pitfalls" title="Chapter 5. Pitfalls">Pitfalls</a>.
</p><p>
The back matter contains several appendices that cover a <a class="xref" href="#quick" title="Appendix A. AspectJ Quick Reference">AspectJ Quick Reference</a> to the language's syntax, a more
in depth coverage of its <a class="xref" href="#semantics" title="Appendix B. Language Semantics">Semantics</a>,
and a description of the latitude enjoyed by its <a class="xref" href="#implementation" title="Appendix C. Implementation Notes">Implementation Notes</a>.
</p></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="starting"></a>Chapter 1. Getting Started with AspectJ</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#starting-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#starting-aspectj">Introduction to AspectJ</a></span></dt><dd><dl><dt><span class="sect2"><a href="#the-dynamic-join-point-model">The Dynamic Join Point Model</a></span></dt><dt><span class="sect2"><a href="#pointcuts">Pointcuts</a></span></dt><dt><span class="sect2"><a href="#advice">Advice</a></span></dt><dt><span class="sect2"><a href="#inter-type-declarations">Inter-type declarations</a></span></dt><dt><span class="sect2"><a href="#aspects">Aspects</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-development">Development Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing">Tracing</a></span></dt><dt><span class="sect2"><a href="#profiling-and-logging">Profiling and Logging</a></span></dt><dt><span class="sect2"><a href="#pre-and-post-conditions">Pre- and Post-Conditions</a></span></dt><dt><span class="sect2"><a href="#contract-enforcement">Contract Enforcement</a></span></dt><dt><span class="sect2"><a href="#configuration-management">Configuration Management</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-production">Production Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#change-monitoring">Change Monitoring</a></span></dt><dt><span class="sect2"><a href="#context-passing">Context Passing</a></span></dt><dt><span class="sect2"><a href="#starting-production-consistentBehavior">Providing Consistent Behavior</a></span></dt></dl></dd><dt><span class="sect1"><a href="#starting-conclusion">Conclusion</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="starting-intro"></a>Introduction</h2></div></div></div><p>
Many software developers are attracted to the idea of aspect-oriented
programming (AOP) but unsure about how to begin using the
technology. They recognize the concept of crosscutting concerns, and
know that they have had problems with the implementation of such
concerns in the past. But there are many questions about how to adopt
AOP into the development process. Common questions include:
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem"><p>Can I use aspects in my existing code?</p></li><li class="listitem"><p>
What kinds of benefits can I expect to get from using aspects?
</p></li><li class="listitem"><p>How do I find aspects in my programs?</p></li><li class="listitem"><p>How steep is the learning curve for AOP?</p></li><li class="listitem"><p>What are the risks of using this new technology?</p></li></ul></div><p>
</p><p>
This chapter addresses these questions in the context of AspectJ: a
general-purpose aspect-oriented extension to Java. A series of
abridged examples illustrate the kinds of aspects programmers may
want to implement using AspectJ and the benefits associated with
doing so. Readers who would like to understand the examples in more
detail, or who want to learn how to program examples like these, can
find more complete examples and supporting material linked from the
AspectJ web site ( <a class="ulink" href="http://eclipse.org/aspectj" target="_top">http://eclipse.org/aspectj</a> ).
</p><p>
A significant risk in adopting any new technology is going too far
too fast. Concern about this risk causes many organizations to be
conservative about adopting new technology. To address this issue,
the examples in this chapter are grouped into three broad categories,
with aspects that are easier to adopt into existing development
projects coming earlier in this chapter. The next section, <a class="xref" href="#starting-aspectj" title="Introduction to AspectJ">Introduction to AspectJ</a>, we present the core of AspectJ's
features, and in <a class="xref" href="#starting-development" title="Development Aspects">Development Aspects</a>, we present
aspects that facilitate tasks such as debugging, testing and
performance tuning of applications. And, in the section following,
<a class="xref" href="#starting-production" title="Production Aspects">Production Aspects</a>, we present aspects that
implement crosscutting functionality common in Java applications. We
will defer discussing a third category of aspects, reusable aspects,
until <a class="xref" href="#language" title="Chapter 2. The AspectJ Language">The AspectJ Language</a>.
</p><p>
These categories are informal, and this ordering is not the only way
to adopt AspectJ. Some developers may want to use a production aspect
right away. But our experience with current AspectJ users suggests
that this is one ordering that allows developers to get experience
with (and benefit from) AOP technology quickly, while also minimizing
risk.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="starting-aspectj"></a>Introduction to AspectJ</h2></div></div></div><p>
This section presents a brief introduction to the features of AspectJ
used later in this chapter. These features are at the core of the
language, but this is by no means a complete overview of AspectJ.
</p><p>
The features are presented using a simple figure editor system. A
<code class="classname">Figure</code> consists of a number of
<code class="classname">FigureElements</code>, which can be either
<code class="classname">Point</code>s or <code class="classname">Line</code>s. The
<code class="classname">Figure</code> class provides factory services. There
is also a <code class="classname">Display</code>. Most example programs later
in this chapter are based on this system as well.
</p><p>
</p><div class="mediaobject"><img src="figureUML.gif"><div class="caption"><p>
UML for the <code class="literal">FigureEditor</code> example
</p></div></div><p>
</p><p>
The motivation for AspectJ (and likewise for aspect-oriented
programming) is the realization that there are issues or concerns
that are not well captured by traditional programming
methodologies. Consider the problem of enforcing a security policy in
some application. By its nature, security cuts across many of the
natural units of modularity of the application. Moreover, the
security policy must be uniformly applied to any additions as the
application evolves. And the security policy that is being applied
might itself evolve. Capturing concerns like a security policy in a
disciplined way is difficult and error-prone in a traditional
programming language.
</p><p>
Concerns like security cut across the natural units of
modularity. For object-oriented programming languages, the natural
unit of modularity is the class. But in object-oriented programming
languages, crosscutting concerns are not easily turned into classes
precisely because they cut across classes, and so these aren't
reusable, they can't be refined or inherited, they are spread through
out the program in an undisciplined way, in short, they are difficult
to work with.
</p><p>
Aspect-oriented programming is a way of modularizing crosscutting
concerns much like object-oriented programming is a way of
modularizing common concerns. AspectJ is an implementation of
aspect-oriented programming for Java.
</p><p>
AspectJ adds to Java just one new concept, a join point -- and that's
really just a name for an existing Java concept. It adds to Java
only a few new constructs: pointcuts, advice, inter-type declarations
and aspects. Pointcuts and advice dynamically affect program flow,
inter-type declarations statically affects a program's class
hierarchy, and aspects encapsulate these new constructs.
</p><p>
A <span class="emphasis"><em>join point</em></span> is a well-defined point in the
program flow. A <span class="emphasis"><em>pointcut</em></span> picks out certain join
points and values at those points. A piece of
<span class="emphasis"><em>advice</em></span> is code that is executed when a join
point is reached. These are the dynamic parts of AspectJ.
</p><p>
AspectJ also has different kinds of <span class="emphasis"><em>inter-type
declarations</em></span> that allow the programmer to modify a
program's static structure, namely, the members of its classes and
the relationship between classes.
</p><p>
AspectJ's <span class="emphasis"><em>aspect</em></span> are the unit of modularity for
crosscutting concerns. They behave somewhat like Java classes, but
may also include pointcuts, advice and inter-type declarations.
</p><p>
In the sections immediately following, we are first going to look at
join points and how they compose into pointcuts. Then we will look at
advice, the code which is run when a pointcut is reached. We will see
how to combine pointcuts and advice into aspects, AspectJ's reusable,
inheritable unit of modularity. Lastly, we will look at how to use
inter-type declarations to deal with crosscutting concerns of a
program's class structure.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="the-dynamic-join-point-model"></a>The Dynamic Join Point Model</h3></div></div></div><p>
A critical element in the design of any aspect-oriented language is
the join point model. The join point model provides the common
frame of reference that makes it possible to define the dynamic
structure of crosscutting concerns. This chapter describes
AspectJ's dynamic join points, in which join points are certain
well-defined points in the execution of the program.
</p><p>
AspectJ provides for many kinds of join points, but this chapter
discusses only one of them: method call join points. A method call
join point encompasses the actions of an object receiving a method
call. It includes all the actions that comprise a method call,
starting after all arguments are evaluated up to and including
return (either normally or by throwing an exception).
</p><p>
Each method call at runtime is a different join point, even if it
comes from the same call expression in the program. Many other
join points may run while a method call join point is executing --
all the join points that happen while executing the method body,
and in those methods called from the body. We say that these join
points execute in the <span class="emphasis"><em>dynamic context</em></span> of the
original call join point.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcuts"></a>Pointcuts</h3></div></div></div><p>
In AspectJ, <span class="emphasis"><em>pointcuts</em></span> pick out certain join
points in the program flow. For example, the pointcut
</p><pre class="programlisting">
call(void Point.setX(int))
</pre><p>
picks out each join point that is a call to a method that has the
signature <code class="literal">void Point.setX(int)</code> — that is,
<code class="classname">Point</code>'s void <code class="function">setX</code>
method with a single <code class="literal">int</code> parameter.
</p><p>
A pointcut can be built out of other pointcuts with and, or, and
not (spelled <code class="literal">&&</code>, <code class="literal">||</code>,
and <code class="literal">!</code>). For example:
</p><pre class="programlisting">
call(void Point.setX(int)) ||
call(void Point.setY(int))
</pre><p>
picks out each join point that is either a call to
<code class="function">setX</code> or a call to <code class="function">setY</code>.
</p><p>
Pointcuts can identify join points from many different types
— in other words, they can crosscut types. For example,
</p><pre class="programlisting">
call(void FigureElement.setXY(int,int)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point));
</pre><p>
picks out each join point that is a call to one of five methods
(the first of which is an interface method, by the way).
</p><p>
In our example system, this pointcut captures all the join points
when a <code class="classname">FigureElement</code> moves. While this is a
useful way to specify this crosscutting concern, it is a bit of a
mouthful. So AspectJ allows programmers to define their own named
pointcuts with the <code class="literal">pointcut</code> form. So the
following declares a new, named pointcut:
</p><pre class="programlisting">
pointcut move():
call(void FigureElement.setXY(int,int)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point));
</pre><p>
and whenever this definition is visible, the programmer can simply
use <code class="literal">move()</code> to capture this complicated
pointcut.
</p><p>
The previous pointcuts are all based on explicit enumeration of a
set of method signatures. We sometimes call this
<span class="emphasis"><em>name-based</em></span> crosscutting. AspectJ also
provides mechanisms that enable specifying a pointcut in terms of
properties of methods other than their exact name. We call this
<span class="emphasis"><em>property-based</em></span> crosscutting. The simplest of
these involve using wildcards in certain fields of the method
signature. For example, the pointcut
</p><pre class="programlisting">
call(void Figure.make*(..))
</pre><p>
picks out each join point that's a call to a void method defined
on <code class="classname">Figure</code> whose the name begins with
"<code class="literal">make</code>" regardless of the method's parameters.
In our system, this picks out calls to the factory methods
<code class="function">makePoint</code> and <code class="function">makeLine</code>.
The pointcut
</p><pre class="programlisting">
call(public * Figure.* (..))
</pre><p>
picks out each call to <code class="classname">Figure</code>'s public
methods.
</p><p>
But wildcards aren't the only properties AspectJ supports.
Another pointcut, <code class="function">cflow</code>, identifies join
points based on whether they occur in the dynamic context of
other join points. So
</p><pre class="programlisting">
cflow(move())
</pre><p>
picks out each join point that occurs in the dynamic context of
the join points picked out by <code class="literal">move()</code>, our named
pointcut defined above. So this picks out each join points that
occurrs between when a move method is called and when it returns
(either normally or by throwing an exception).
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice"></a>Advice</h3></div></div></div><p>
So pointcuts pick out join points. But they don't
<span class="emphasis"><em>do</em></span> anything apart from picking out join
points. To actually implement crosscutting behavior, we use
advice. Advice brings together a pointcut (to pick out join
points) and a body of code (to run at each of those join points).
</p><p>
AspectJ has several different kinds of advice. <span class="emphasis"><em>Before
advice</em></span> runs as a join point is reached, before the
program proceeds with the join point. For example, before advice
on a method call join point runs before the actual method starts
running, just after the arguments to the method call are evaluated.
</p><pre class="programlisting">
before(): move() {
System.out.println("about to move");
}
</pre><p>
<span class="emphasis"><em>After advice</em></span> on a particular join point runs
after the program proceeds with that join point. For example,
after advice on a method call join point runs after the method body
has run, just before before control is returned to the caller.
Because Java programs can leave a join point 'normally' or by
throwing an exception, there are three kinds of after advice:
<code class="literal">after returning</code>, <code class="literal">after
throwing</code>, and plain <code class="literal">after</code> (which runs
after returning <span class="emphasis"><em>or</em></span> throwing, like Java's
<code class="literal">finally</code>).
</p><pre class="programlisting">
after() returning: move() {
System.out.println("just successfully moved");
}
</pre><p>
<span class="emphasis"><em>Around advice</em></span> on a join point runs as the join
point is reached, and has explicit control over whether the program
proceeds with the join point. Around advice is not discussed in
this section.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm160"></a>Exposing Context in Pointcuts</h4></div></div></div><p>
Pointcuts not only pick out join points, they can also expose
part of the execution context at their join points. Values
exposed by a pointcut can be used in the body of advice
declarations.
</p><p>
An advice declaration has a parameter list (like a method) that
gives names to all the pieces of context that it uses. For
example, the after advice
</p><pre class="programlisting">
after(FigureElement fe, int x, int y) returning:
...SomePointcut... {
...SomeBody...
}
</pre><p>
uses three pieces of exposed context, a
<code class="literal">FigureElement</code> named fe, and two
<code class="literal">int</code>s named x and y.
</p><p>
The body of the advice uses the names just like method
parameters, so
</p><pre class="programlisting">
after(FigureElement fe, int x, int y) returning:
...SomePointcut... {
System.out.println(fe + " moved to (" + x + ", " + y + ")");
}
</pre><p>
The advice's pointcut publishes the values for the advice's
arguments. The three primitive pointcuts
<code class="literal">this</code>, <code class="literal">target</code> and
<code class="literal">args</code> are used to publish these values. So now
we can write the complete piece of advice:
</p><pre class="programlisting">
after(FigureElement fe, int x, int y) returning:
call(void FigureElement.setXY(int, int))
&& target(fe)
&& args(x, y) {
System.out.println(fe + " moved to (" + x + ", " + y + ")");
}
</pre><p>
The pointcut exposes three values from calls to
<code class="function">setXY</code>: the target
<code class="classname">FigureElement</code> -- which it publishes as
<code class="literal">fe</code>, so it becomes the first argument to the
after advice -- and the two int arguments -- which it publishes
as <code class="literal">x</code> and <code class="literal">y</code>, so they become
the second and third argument to the after advice.
</p><p>
So the advice prints the figure element
that was moved and its new <code class="literal">x</code> and
<code class="literal">y</code> coordinates after each
<code class="classname">setXY</code> method call.
</p><p>
A named pointcut may have parameters like a piece of advice.
When the named pointcut is used (by advice, or in another named
pointcut), it publishes its context by name just like the
<code class="literal">this</code>, <code class="literal">target</code> and
<code class="literal">args</code> pointcut. So another way to write the
above advice is
</p><pre class="programlisting">
pointcut setXY(FigureElement fe, int x, int y):
call(void FigureElement.setXY(int, int))
&& target(fe)
&& args(x, y);
after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) {
System.out.println(fe + " moved to (" + x + ", " + y + ").");
}
</pre></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="inter-type-declarations"></a>Inter-type declarations</h3></div></div></div><p>
Inter-type declarations in AspectJ are declarations that cut across
classes and their hierarchies. They may declare members that cut
across multiple classes, or change the inheritance relationship
between classes. Unlike advice, which operates primarily
dynamically, introduction operates statically, at compile-time.
</p><p>
Consider the problem of expressing a capability shared by some
existing classes that are already part of a class hierarchy,
i.e. they already extend a class. In Java, one creates an
interface that captures this new capability, and then adds to
<span class="emphasis"><em>each affected class</em></span> a method that implements
this interface.
</p><p>
AspectJ can express the concern in one place, by using inter-type
declarations. The aspect declares the methods and fields that are
necessary to implement the new capability, and associates the
methods and fields to the existing classes.
</p><p>
Suppose we want to have <code class="classname">Screen</code> objects
observe changes to <code class="classname">Point</code> objects, where
<code class="classname">Point</code> is an existing class. We can implement
this by writing an aspect declaring that the class Point
<code class="classname">Point</code> has an instance field,
<code class="varname">observers</code>, that keeps track of the
<code class="classname">Screen</code> objects that are observing
<code class="classname">Point</code>s.
</p><pre class="programlisting">
aspect PointObserving {
private Vector Point.observers = new Vector();
...
}
</pre><p>
The <code class="literal">observers</code> field is private, so only
<code class="classname">PointObserving</code> can see it. So observers are
added or removed with the static methods
<code class="function">addObserver</code> and
<code class="function">removeObserver</code> on the aspect.
</p><pre class="programlisting">
aspect PointObserving {
private Vector Point.observers = new Vector();
public static void addObserver(Point p, Screen s) {
p.observers.add(s);
}
public static void removeObserver(Point p, Screen s) {
p.observers.remove(s);
}
...
}
</pre><p>
Along with this, we can define a pointcut
<code class="function">changes</code> that defines what we want to observe,
and the after advice defines what we want to do when we observe a
change.
</p><pre class="programlisting">
aspect PointObserving {
private Vector Point.observers = new Vector();
public static void addObserver(Point p, Screen s) {
p.observers.add(s);
}
public static void removeObserver(Point p, Screen s) {
p.observers.remove(s);
}
pointcut changes(Point p): target(p) && call(void Point.set*(int));
after(Point p): changes(p) {
Iterator iter = p.observers.iterator();
while ( iter.hasNext() ) {
updateObserver(p, (Screen)iter.next());
}
}
static void updateObserver(Point p, Screen s) {
s.display(p);
}
}
</pre><p>
Note that neither <code class="classname">Screen</code>'s nor
<code class="classname">Point</code>'s code has to be modified, and that
all the changes needed to support this new capability are local to
this aspect.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="aspects"></a>Aspects</h3></div></div></div><p>
Aspects wrap up pointcuts, advice, and inter-type declarations in a
a modular unit of crosscutting implementation. It is defined very
much like a class, and can have methods, fields, and initializers
in addition to the crosscutting members. Because only aspects may
include these crosscutting members, the declaration of these
effects is localized.
</p><p>
Like classes, aspects may be instantiated, but AspectJ controls how
that instantiation happens -- so you can't use Java's
<code class="literal">new</code> form to build new aspect instances. By
default, each aspect is a singleton, so one aspect instance is
created. This means that advice may use non-static fields of the
aspect, if it needs to keep state around:
</p><pre class="programlisting">
aspect Logging {
OutputStream logStream = System.err;
before(): move() {
logStream.println("about to move");
}
}
</pre><p>
Aspects may also have more complicated rules for instantiation, but
these will be described in a later chapter.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="starting-development"></a>Development Aspects</h2></div></div></div><p>
The next two sections present the use of aspects in increasingly
sophisticated ways. Development aspects are easily removed from
production builds. Production aspects are intended to be used in
both development and in production, but tend to affect only a few
classes.
</p><p>
This section presents examples of aspects that can be used during
development of Java applications. These aspects facilitate debugging,
testing and performance tuning work. The aspects define behavior that
ranges from simple tracing, to profiling, to testing of internal
consistency within the application. Using AspectJ makes it possible
to cleanly modularize this kind of functionality, thereby making it
possible to easily enable and disable the functionality when desired.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="tracing"></a>Tracing</h3></div></div></div><p>
This first example shows how to increase the visibility of the
internal workings of a program. It is a simple tracing aspect that
prints a message at specified method calls. In our figure editor
example, one such aspect might simply trace whenever points are
drawn.
</p><pre class="programlisting">
aspect SimpleTracing {
pointcut tracedCall():
call(void FigureElement.draw(GraphicsContext));
before(): tracedCall() {
System.out.println("Entering: " + thisJoinPoint);
}
}
</pre><p>
This code makes use of the <code class="literal">thisJoinPoint</code> special
variable. Within all advice bodies this variable is bound to an
object that describes the current join point. The effect of this
code is to print a line like the following every time a figure
element receives a <code class="function">draw</code> method call:
</p><pre class="programlisting">
Entering: call(void FigureElement.draw(GraphicsContext))
</pre><p>
To understand the benefit of coding this with AspectJ consider
changing the set of method calls that are traced. With AspectJ,
this just requires editing the definition of the
<code class="function">tracedCalls</code> pointcut and recompiling. The
individual methods that are traced do not need to be edited.
</p><p>
When debugging, programmers often invest considerable effort in
figuring out a good set of trace points to use when looking for a
particular kind of problem. When debugging is complete or appears
to be complete it is frustrating to have to lose that investment by
deleting trace statements from the code. The alternative of just
commenting them out makes the code look bad, and can cause trace
statements for one kind of debugging to get confused with trace
statements for another kind of debugging.
</p><p>
With AspectJ it is easy to both preserve the work of designing a
good set of trace points and disable the tracing when it isn t
being used. This is done by writing an aspect specifically for that
tracing mode, and removing that aspect from the compilation when it
is not needed.
</p><p>
This ability to concisely implement and reuse debugging
configurations that have proven useful in the past is a direct
result of AspectJ modularizing a crosscutting design element the
set of methods that are appropriate to trace when looking for a
given kind of information.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="profiling-and-logging"></a>Profiling and Logging</h3></div></div></div><p>
Our second example shows you how to do some very specific
profiling. Although many sophisticated profiling tools are
available, and these can gather a variety of information and
display the results in useful ways, you may sometimes want to
profile or log some very specific behavior. In these cases, it is
often possible to write a simple aspect similar to the ones above
to do the job.
</p><p>
For example, the following aspect counts the number of calls to the
<code class="function">rotate</code> method on a <code class="classname">Line</code>
and the number of calls to the <code class="function">set*</code> methods of
a <code class="classname">Point</code> that happen within the control flow
of those calls to <code class="function">rotate</code>:
</p><pre class="programlisting">
aspect SetsInRotateCounting {
int rotateCount = 0;
int setCount = 0;
before(): call(void Line.rotate(double)) {
rotateCount++;
}
before(): call(void Point.set*(int))
&& cflow(call(void Line.rotate(double))) {
setCount++;
}
}
</pre><p>
In effect, this aspect allows the programmer to ask very specific
questions like
</p><div class="blockquote"><blockquote class="blockquote">
How many times is the <code class="function">rotate</code>
method defined on <code class="classname">Line</code> objects called?
</blockquote></div><p>
and
</p><div class="blockquote"><blockquote class="blockquote">
How many times are methods defined on
<code class="classname">Point</code> objects whose name begins with
"<code class="function">set</code>" called in fulfilling those rotate
calls?
</blockquote></div><p>
questions it may be difficult to express using standard
profiling or logging tools.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pre-and-post-conditions"></a>Pre- and Post-Conditions</h3></div></div></div><p>
Many programmers use the "Design by Contract" style popularized by
Bertand Meyer in <em class="citetitle">Object-Oriented Software Construction,
2/e</em>. In this style of programming, explicit
pre-conditions test that callers of a method call it properly and
explicit post-conditions test that methods properly do the work
they are supposed to.
</p><p>
AspectJ makes it possible to implement pre- and post-condition
testing in modular form. For example, this code
</p><pre class="programlisting">
aspect PointBoundsChecking {
pointcut setX(int x):
(call(void FigureElement.setXY(int, int)) && args(x, *))
|| (call(void Point.setX(int)) && args(x));
pointcut setY(int y):
(call(void FigureElement.setXY(int, int)) && args(*, y))
|| (call(void Point.setY(int)) && args(y));
before(int x): setX(x) {
if ( x < MIN_X || x > MAX_X )
throw new IllegalArgumentException("x is out of bounds.");
}
before(int y): setY(y) {
if ( y < MIN_Y || y > MAX_Y )
throw new IllegalArgumentException("y is out of bounds.");
}
}
</pre><p>
implements the bounds checking aspect of pre-condition testing for
operations that move points. Notice that the
<code class="function">setX</code> pointcut refers to all the operations
that can set a Point's <code class="literal">x</code> coordinate; this
includes the <code class="function">setX</code> method, as well as half of
the <code class="function">setXY</code> method. In this sense the
<code class="function">setX</code> pointcut can be seen as involving very
fine-grained crosscutting — it names the the
<code class="function">setX</code> method and half of the
<code class="function">setXY</code> method.
</p><p>
Even though pre- and post-condition testing aspects can often be
used only during testing, in some cases developers may wish to
include them in the production build as well. Again, because
AspectJ makes it possible to modularize these crosscutting concerns
cleanly, it gives developers good control over this decision.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="contract-enforcement"></a>Contract Enforcement</h3></div></div></div><p>
The property-based crosscutting mechanisms can be very useful in
defining more sophisticated contract enforcement. One very powerful
use of these mechanisms is to identify method calls that, in a
correct program, should not exist. For example, the following
aspect enforces the constraint that only the well-known factory
methods can add an element to the registry of figure
elements. Enforcing this constraint ensures that no figure element
is added to the registry more than once.
</p><pre class="programlisting">
aspect RegistrationProtection {
pointcut register(): call(void Registry.register(FigureElement));
pointcut canRegister(): withincode(static * FigureElement.make*(..));
before(): register() && !canRegister() {
throw new IllegalAccessException("Illegal call " + thisJoinPoint);
}
}
</pre><p>
This aspect uses the withincode primitive pointcut to denote all
join points that occur within the body of the factory methods on
<code class="classname">FigureElement</code> (the methods with names that
begin with "<code class="literal">make</code>"). This is a property-based
pointcut because it identifies join points based not on their
signature, but rather on the property that they occur specifically
within the code of another method. The before advice declaration
effectively says signal an error for any calls to register that are
not within the factory methods.
</p><p>
This advice throws a runtime exception at certain join points, but
AspectJ can do better. Using the <code class="literal">declare error</code>
form, we can have the <span class="emphasis"><em>compiler</em></span> signal the
error.
</p><pre class="programlisting">
aspect RegistrationProtection {
pointcut register(): call(void Registry.register(FigureElement));
pointcut canRegister(): withincode(static * FigureElement.make*(..));
declare error: register() && !canRegister(): "Illegal call"
}
</pre><p>
When using this aspect, it is impossible for the compiler to
compile programs with these illegal calls. This early detection is
not always possible. In this case, since we depend only on static
information (the <code class="literal">withincode</code> pointcut picks out
join points totally based on their code, and the
<code class="literal">call</code> pointcut here picks out join points
statically). Other enforcement, such as the precondition
enforcement, above, does require dynamic information such as the
runtime value of parameters.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="configuration-management"></a>Configuration Management</h3></div></div></div><p>
Configuration management for aspects can be handled using a variety
of make-file like techniques. To work with optional aspects, the
programmer can simply define their make files to either include the
aspect in the call to the AspectJ compiler or not, as desired.
</p><p>
Developers who want to be certain that no aspects are included in
the production build can do so by configuring their make files so
that they use a traditional Java compiler for production builds. To
make it easy to write such make files, the AspectJ compiler has a
command-line interface that is consistent with ordinary Java
compilers.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="starting-production"></a>Production Aspects</h2></div></div></div><p>
This section presents examples of aspects that are inherently
intended to be included in the production builds of an application.
Production aspects tend to add functionality to an application
rather than merely adding more visibility of the internals of a
program. Again, we begin with name-based aspects and follow with
property-based aspects. Name-based production aspects tend to
affect only a small number of methods. For this reason, they are a
good next step for projects adopting AspectJ. But even though they
tend to be small and simple, they can often have a significant
effect in terms of making the program easier to understand and
maintain.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="change-monitoring"></a>Change Monitoring</h3></div></div></div><p>
The first example production aspect shows how one might implement
some simple functionality where it is problematic to try and do it
explicitly. It supports the code that refreshes the display. The
role of the aspect is to maintain a dirty bit indicating whether or
not an object has moved since the last time the display was
refreshed.
</p><p>
Implementing this functionality as an aspect is straightforward.
The <code class="function">testAndClear</code> method is called by the
display code to find out whether a figure element has moved
recently. This method returns the current state of the dirty flag
and resets it to false. The pointcut <code class="function">move</code>
captures all the method calls that can move a figure element. The
after advice on <code class="function">move</code> sets the dirty flag
whenever an object moves.
</p><pre class="programlisting">
aspect MoveTracking {
private static boolean dirty = false;
public static boolean testAndClear() {
boolean result = dirty;
dirty = false;
return result;
}
pointcut move():
call(void FigureElement.setXY(int, int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int));
after() returning: move() {
dirty = true;
}
}
</pre><p>
Even this simple example serves to illustrate some of the important
benefits of using AspectJ in production code. Consider implementing
this functionality with ordinary Java: there would likely be a
helper class that contained the <code class="literal">dirty</code> flag, the
<code class="function">testAndClear</code> method, as well as a
<code class="function">setFlag</code> method. Each of the methods that could
move a figure element would include a call to the
<code class="function">setFlag</code> method. Those calls, or rather the
concept that those calls should happen at each move operation, are
the crosscutting concern in this case.
</p><p>
The AspectJ implementation has several advantages over the standard
implementation:
</p><p>
<span class="emphasis"><em>The structure of the crosscutting concern is captured
explicitly.</em></span> The moves pointcut clearly states all the
methods involved, so the programmer reading the code sees not just
individual calls to <code class="literal">setFlag</code>, but instead sees
the real structure of the code. The IDE support included with
AspectJ automatically reminds the programmer that this aspect
advises each of the methods involved. The IDE support also
provides commands to jump to the advice from the method and
vice-versa.
</p><p>
<span class="emphasis"><em>Evolution is easier.</em></span> If, for example, the
aspect needs to be revised to record not just that some figure
element moved, but rather to record exactly which figure elements
moved, the change would be entirely local to the aspect. The
pointcut would be updated to expose the object being moved, and the
advice would be updated to record that object. The paper
<em class="citetitle">An Overview of AspectJ</em> (available linked off
of the AspectJ web site -- <a class="ulink" href="http://eclipse.org/aspectj" target="_top">http://eclipse.org/aspectj</a>), presented at ECOOP
2001, presents a detailed discussion of various ways this aspect
could be expected to evolve.
</p><p>
<span class="emphasis"><em>The functionality is easy to plug in and out.</em></span>
Just as with development aspects, production aspects may need to be
removed from the system, either because the functionality is no
longer needed at all, or because it is not needed in certain
configurations of a system. Because the functionality is
modularized in a single aspect this is easy to do.
</p><p>
<span class="emphasis"><em>The implementation is more stable.</em></span> If, for
example, the programmer adds a subclass of
<code class="classname">Line</code> that overrides the existing methods,
this advice in this aspect will still apply. In the ordinary Java
implementation the programmer would have to remember to add the
call to <code class="function">setFlag</code> in the new overriding
method. This benefit is often even more compelling for
property-based aspects (see the section <a class="xref" href="#starting-production-consistentBehavior" title="Providing Consistent Behavior">Providing Consistent Behavior</a>).
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="context-passing"></a>Context Passing</h3></div></div></div><p>
The crosscutting structure of context passing can be a significant
source of complexity in Java programs. Consider implementing
functionality that would allow a client of the figure editor (a
program client rather than a human) to set the color of any figure
elements that are created. Typically this requires passing a color,
or a color factory, from the client, down through the calls that
lead to the figure element factory. All programmers are familiar
with the inconvenience of adding a first argument to a number of
methods just to pass this kind of context information.
</p><p>
Using AspectJ, this kind of context passing can be implemented in a
modular way. The following code adds after advice that runs only
when the factory methods of <code class="classname">Figure</code> are
called in the control flow of a method on a
<code class="classname">ColorControllingClient</code>.
</p><pre class="programlisting">
aspect ColorControl {
pointcut CCClientCflow(ColorControllingClient client):
cflow(call(* * (..)) && target(client));
pointcut make(): call(FigureElement Figure.make*(..));
after (ColorControllingClient c) returning (FigureElement fe):
make() && CCClientCflow(c) {
fe.setColor(c.colorFor(fe));
}
}
</pre><p>
This aspect affects only a small number of methods, but note that
the non-AOP implementation of this functionality might require
editing many more methods, specifically, all the methods in the
control flow from the client to the factory. This is a benefit
common to many property-based aspects while the aspect is short and
affects only a modest number of benefits, the complexity the aspect
saves is potentially much larger.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="starting-production-consistentBehavior"></a>Providing Consistent Behavior</h3></div></div></div><p>
This example shows how a property-based aspect can be used to
provide consistent handling of functionality across a large set of
operations. This aspect ensures that all public methods of the
<code class="literal">com.bigboxco</code> package log any Errors they throw
to their caller (in Java, an Error is like an Exception, but it
indicates that something really bad and usually unrecoverable has
happened). The <code class="function">publicMethodCall</code> pointcut
captures the public method calls of the package, and the after
advice runs whenever one of those calls throws an Error. The advice
logs that Error and then the throw resumes.
</p><pre class="programlisting">
aspect PublicErrorLogging {
Log log = new Log();
pointcut publicMethodCall():
call(public * com.bigboxco.*.*(..));
after() throwing (Error e): publicMethodCall() {
log.write(e);
}
}
</pre><p>
In some cases this aspect can log an exception twice. This happens
if code inside the <code class="literal">com.bigboxco</code> package itself
calls a public method of the package. In that case this code will
log the error at both the outermost call into the
<code class="literal">com.bigboxco</code> package and the re-entrant
call. The <code class="function">cflow</code> primitive pointcut can be used
in a nice way to exclude these re-entrant calls:</p><pre class="programlisting">
after() throwing (Error e):
publicMethodCall() && !cflow(publicMethodCall()) {
log.write(e);
}
</pre><p>
The following aspect is taken from work on the AspectJ compiler.
The aspect advises about 35 methods in the
<code class="classname">JavaParser</code> class. The individual methods
handle each of the different kinds of elements that must be
parsed. They have names like <code class="function">parseMethodDec</code>,
<code class="function">parseThrows</code>, and
<code class="function">parseExpr</code>.
</p><pre class="programlisting">
aspect ContextFilling {
pointcut parse(JavaParser jp):
call(* JavaParser.parse*(..))
&& target(jp)
&& !call(Stmt parseVarDec(boolean)); // var decs
// are tricky
around(JavaParser jp) returns ASTObject: parse(jp) {
Token beginToken = jp.peekToken();
ASTObject ret = proceed(jp);
if (ret != null) jp.addContext(ret, beginToken);
return ret;
}
}
</pre><p>
This example exhibits a property found in many aspects with large
property-based pointcuts. In addition to a general property based
pattern <code class="literal">call(* JavaParser.parse*(..))</code> it
includes an exception to the pattern <code class="literal">!call(Stmt
parseVarDec(boolean))</code>. The exclusion of
<code class="function">parseVarDec</code> happens because the parsing of
variable declarations in Java is too complex to fit with the clean
pattern of the other <code class="function">parse*</code> methods. Even with
the explicit exclusion this aspect is a clear expression of a clean
crosscutting modularity. Namely that all
<code class="function">parse*</code> methods that return
<code class="classname">ASTObjects</code>, except for
<code class="function">parseVarDec</code> share a common behavior for
establishing the parse context of their result.
</p><p>
The process of writing an aspect with a large property-based
pointcut, and of developing the appropriate exceptions can clarify
the structure of the system. This is especially true, as in this
case, when refactoring existing code to use aspects. When we first
looked at the code for this aspect, we were able to use the IDE
support provided in AJDE for JBuilder to see what methods the
aspect was advising compared to our manual coding. We quickly
discovered that there were a dozen places where the aspect advice
was in effect but we had not manually inserted the required
functionality. Two of these were bugs in our prior non-AOP
implementation of the parser. The other ten were needless
performance optimizations. So, here, refactoring the code to
express the crosscutting structure of the aspect explicitly made
the code more concise and eliminated latent bugs.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="starting-conclusion"></a>Conclusion</h2></div></div></div><p>
AspectJ is a simple and practical aspect-oriented extension to
Java. With just a few new constructs, AspectJ provides support for
modular implementation of a range of crosscutting concerns.
</p><p>
Adoption of AspectJ into an existing Java development project can be
a straightforward and incremental task. One path is to begin by using
only development aspects, going on to using production aspects and
then reusable aspects after building up experience with
AspectJ. Adoption can follow other paths as well. For example, some
developers will benefit from using production aspects right
away. Others may be able to write clean reusable aspects almost right
away.
</p><p>
AspectJ enables both name-based and property based crosscutting.
Aspects that use name-based crosscutting tend to affect a small
number of other classes. But despite their small scale, they can
often eliminate significant complexity compared to an ordinary Java
implementation. Aspects that use property-based crosscutting can
have small or large scale.
</p><p>
Using AspectJ results in clean well-modularized implementations of
crosscutting concerns. When written as an AspectJ aspect the
structure of a crosscutting concern is explicit and easy to
understand. Aspects are also highly modular, making it possible to
develop plug-and-play implementations of crosscutting
functionality.
</p><p>
AspectJ provides more functionality than was covered by this short
introduction. The next chapter, <a class="xref" href="#language" title="Chapter 2. The AspectJ Language">The AspectJ Language</a>,
covers in detail more of the features of the AspectJ language. The
following chapter, <a class="xref" href="#examples" title="Chapter 3. Examples">Examples</a>, then presents some
carefully chosen examples that show you how AspectJ might be used. We
recommend that you read the next two chapters carefully before
deciding to adopt AspectJ into a project.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="language"></a>Chapter 2. The AspectJ Language</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#language-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#language-anatomy">The Anatomy of an Aspect</a></span></dt><dd><dl><dt><span class="sect2"><a href="#an-example-aspect">An Example Aspect</a></span></dt><dt><span class="sect2"><a href="#pointcuts">Pointcuts</a></span></dt><dt><span class="sect2"><a href="#advice">Advice</a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-joinPoints">Join Points and Pointcuts</a></span></dt><dd><dl><dt><span class="sect2"><a href="#some-example-pointcuts">Some Example Pointcuts</a></span></dt><dt><span class="sect2"><a href="#call-vs-execution">call vs. execution</a></span></dt><dt><span class="sect2"><a href="#pointcut-composition">Pointcut composition</a></span></dt><dt><span class="sect2"><a href="#pointcut-parameters">Pointcut Parameters</a></span></dt><dt><span class="sect2"><a href="#example">Example: <code class="literal">HandleLiveness</code></a></span></dt><dt><span class="sect2"><a href="#pointcut-best-practice">Writing good pointcuts</a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-advice">Advice</a></span></dt><dt><span class="sect1"><a href="#language-interType">Inter-type declarations</a></span></dt><dd><dl><dt><span class="sect2"><a href="#inter-type-scope">Inter-type Scope</a></span></dt><dt><span class="sect2"><a href="#example-pointassertions">Example: <code class="literal">PointAssertions</code></a></span></dt></dl></dd><dt><span class="sect1"><a href="#language-thisJoinPoint">thisJoinPoint</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-intro"></a>Introduction</h2></div></div></div><p>
The previous chapter, <a class="xref" href="#starting" title="Chapter 1. Getting Started with AspectJ">Getting Started with AspectJ</a>, was a brief
overview of the AspectJ language. You should read this chapter to
understand AspectJ's syntax and semantics. It covers the same
material as the previous chapter, but more completely and in much
more detail.
</p><p>
We will start out by looking at an example aspect that we'll build
out of a pointcut, an introduction, and two pieces of advice. This
example aspect will gives us something concrete to talk about.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-anatomy"></a>The Anatomy of an Aspect</h2></div></div></div><p>
This lesson explains the parts of AspectJ's aspects. By reading this
lesson you will have an overview of what's in an aspect and you will
be exposed to the new terminology introduced by AspectJ.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="an-example-aspect"></a>An Example Aspect</h3></div></div></div><p>
Here's an example of an aspect definition in AspectJ:
</p><pre class="programlisting">
1 aspect FaultHandler {
2
3 private boolean Server.disabled = false;
4
5 private void reportFault() {
6 System.out.println("Failure! Please fix it.");
7 }
8
9 public static void fixServer(Server s) {
10 s.disabled = false;
11 }
12
13 pointcut services(Server s): target(s) && call(public * *(..));
14
15 before(Server s): services(s) {
16 if (s.disabled) throw new DisabledException();
17 }
18
19 after(Server s) throwing (FaultException e): services(s) {
20 s.disabled = true;
21 reportFault();
22 }
23 }
</pre><p>
The <code class="literal">FaultHandler</code> consists of one inter-type
field on <code class="literal">Server</code> (line 03), two methods (lines
05-07 and 09-11), one pointcut definition (line 13), and two pieces
of advice (lines 15-17 and 19-22).
</p><p>
This covers the basics of what aspects can contain. In general,
aspects consist of an association of other program entities,
ordinary variables and methods, pointcut definitions, inter-type declarations,
and advice, where advice may be before, after or around advice. The
remainder of this lesson focuses on those crosscut-related
constructs.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcuts"></a>Pointcuts</h3></div></div></div><p>
AspectJ's pointcut definitions give names to pointcuts. Pointcuts
themselves pick out join points, i.e. interesting points in the
execution of a program. These join points can be method or
constructor invocations and executions, the handling of exceptions,
field assignments and accesses, etc. Take, for example, the
pointcut definition in line 13:
</p><pre class="programlisting">
pointcut services(Server s): target(s) && call(public * *(..))
</pre><p>
This pointcut, named <code class="literal">services</code>, picks out those
points in the execution of the program when
<code class="literal">Server</code> objects have their public methods called.
It also allows anyone using the <code class="literal">services</code>
pointcut to access the <code class="literal">Server</code> object whose
method is being called.
</p><p>
The idea behind this pointcut in the
<code class="literal">FaultHandler</code> aspect is that
fault-handling-related behavior must be triggered on the calls to
public methods. For example, the server may be unable to proceed
with the request because of some fault. The calls of those methods
are, therefore, interesting events for this aspect, in the sense
that certain fault-related things will happen when these events
occur.
</p><p>
Part of the context in which the events occur is exposed by the
formal parameters of the pointcut. In this case, that consists of
objects of type <code class="literal">Server</code>. That formal parameter
is then being used on the right hand side of the declaration in
order to identify which events the pointcut refers to. In this
case, a pointcut picking out join points where a Server is the
target of some operation (target(s)) is being composed
(<code class="literal">&&</code>, meaning and) with a pointcut
picking out call join points (call(...)). The calls are identified
by signatures that can include wild cards. In this case, there are
wild cards in the return type position (first *), in the name
position (second *) and in the argument list position (..); the
only concrete information is given by the qualifier
<code class="literal">public</code>.
</p><p>
Pointcuts pick out arbitrarily large numbers of join points of a
program. But they pick out only a small number of
<span class="emphasis"><em>kinds</em></span> of join points. Those kinds of join
points correspond to some of the most important concepts in
Java. Here is an incomplete list: method call, method execution,
exception handling, instantiation, constructor execution, and
field access. Each kind of join point can be picked out by its
own specialized pointcut that you will learn about in other parts
of this guide.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice"></a>Advice</h3></div></div></div><p>
A piece of advice brings together a pointcut and a body of code to
define aspect implementation that runs at join points picked out by
the pointcut. For example, the advice in lines 15-17 specifies that
the following piece of code
</p><pre class="programlisting">
{
if (s.disabled) throw new DisabledException();
}
</pre><p>
is executed when instances of the <code class="literal">Server</code> class
have their public methods called, as specified by the pointcut
<code class="literal">services</code>. More specifically, it runs when those
calls are made, just before the corresponding methods are executed.
</p><p>
The advice in lines 19-22 defines another piece of implementation
that is executed on the same pointcut:
</p><pre class="programlisting">
{
s.disabled = true;
reportFault();
}
</pre><p>
But this second method executes after those operations throw
exception of type <code class="literal">FaultException</code>.
</p><p>
There are two other variations of after advice: upon successful
return and upon return, either successful or with an exception.
There is also a third kind of advice called around. You will see
those in other parts of this guide.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-joinPoints"></a>Join Points and Pointcuts</h2></div></div></div><p>
Consider the following Java class:
</p><pre class="programlisting">
class Point {
private int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
void setX(int x) { this.x = x; }
void setY(int y) { this.y = y; }
int getX() { return x; }
int getY() { return y; }
}
</pre><p>
In order to get an intuitive understanding of AspectJ's join points
and pointcuts, let's go back to some of the basic principles of
Java. Consider the following a method declaration in class Point:
</p><pre class="programlisting">
void setX(int x) { this.x = x; }
</pre><p>
This piece of program says that when method named
<code class="literal">setX</code> with an <code class="literal">int</code> argument
called on an object of type <code class="literal">Point</code>, then the method
body <code class="literal">{ this.x = x; }</code> is executed. Similarly, the
constructor of the class states that when an object of type
<code class="literal">Point</code> is instantiated through a constructor with
two <code class="literal">int</code> arguments, then the constructor body
<code class="literal">{ this.x = x; this.y = y; }</code> is executed.
</p><p>
One pattern that emerges from these descriptions is
</p><div class="blockquote"><blockquote class="blockquote">
When something happens, then something gets executed.
</blockquote></div><p>
In object-oriented programs, there are several kinds of "things that
happen" that are determined by the language. We call these the join
points of Java. Join points consist of things like method calls,
method executions, object instantiations, constructor executions,
field references and handler executions. (See the <a class="xref" href="#quick" title="Appendix A. AspectJ Quick Reference">AspectJ Quick Reference</a> for a complete listing.)
</p><p>
Pointcuts pick out these join points. For example, the pointcut
</p><pre class="programlisting">
pointcut setter(): target(Point) &&
(call(void setX(int)) ||
call(void setY(int)));
</pre><p>
picks out each call to <code class="literal">setX(int)</code> or
<code class="literal">setY(int)</code> when called on an instance of
<code class="literal">Point</code>. Here's another example:
</p><pre class="programlisting">
pointcut ioHandler(): within(MyClass) && handler(IOException);
</pre><p>
This pointcut picks out each the join point when exceptions of type
<code class="literal">IOException</code> are handled inside the code defined by
class <code class="literal">MyClass</code>.
</p><p>
Pointcut definitions consist of a left-hand side and a right-hand side,
separated by a colon. The left-hand side consists of the pointcut name
and the pointcut parameters (i.e. the data available when the events
happen). The right-hand side consists of the pointcut itself.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="some-example-pointcuts"></a>Some Example Pointcuts</h3></div></div></div><p>
Here are examples of pointcuts picking out
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">when a particular method body executes</span></dt><dd><p>
<code class="literal">execution(void Point.setX(int))</code>
</p></dd><dt><span class="term">when a method is called</span></dt><dd><p>
<code class="literal">call(void Point.setX(int))</code>
</p></dd><dt><span class="term">when an exception handler executes</span></dt><dd><p>
<code class="literal">handler(ArrayOutOfBoundsException)</code>
</p></dd><dt><span class="term">
when the object currently executing
(i.e. <code class="literal">this</code>) is of type
<code class="literal">SomeType</code>
</span></dt><dd><p>
<code class="literal">this(SomeType)</code>
</p></dd><dt><span class="term">
when the target object is of type <code class="literal">SomeType</code>
</span></dt><dd><p>
<code class="literal">target(SomeType)</code>
</p></dd><dt><span class="term">
when the executing code belongs to
class <code class="literal">MyClass</code>
</span></dt><dd><p>
<code class="literal">within(MyClass)</code>
</p></dd><dt><span class="term">
when the join point is in the control flow of a call to a
<code class="literal">Test</code>'s no-argument <code class="literal">main</code>
method
</span></dt><dd><p>
<code class="literal">cflow(call(void Test.main()))</code>
</p></dd></dl></div><p>
Pointcuts compose through the operations <code class="literal">or</code>
("<code class="literal">||</code>"), <code class="literal">and</code>
("<code class="literal">&&</code>") and <code class="literal">not</code>
("<code class="literal">!</code>").
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
It is possible to use wildcards. So
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
<code class="literal">execution(* *(..))</code>
</p></li><li class="listitem"><p>
<code class="literal">call(* set(..))</code>
</p></li></ol></div><p>
means (1) the execution of any method regardless of return or
parameter types, and (2) the call to any method named
<code class="literal">set</code> regardless of return or parameter types
-- in case of overloading there may be more than one such
<code class="literal">set</code> method; this pointcut picks out calls to
all of them.
</p></li><li class="listitem"><p>
You can select elements based on types. For example,
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
<code class="literal">execution(int *())</code>
</p></li><li class="listitem"><p>
<code class="literal">call(* setY(long))</code>
</p></li><li class="listitem"><p>
<code class="literal">call(* Point.setY(int))</code>
</p></li><li class="listitem"><p>
<code class="literal">call(*.new(int, int))</code>
</p></li></ol></div><p>
means (1) the execution of any method with no parameters that
returns an <code class="literal">int</code>, (2) the call to any
<code class="literal">setY</code> method that takes a
<code class="literal">long</code> as an argument, regardless of return
type or declaring type, (3) the call to any of
<code class="literal">Point</code>'s <code class="literal">setY</code> methods that
take an <code class="literal">int</code> as an argument, regardless of
return type, and (4) the call to any classes' constructor, so
long as it takes exactly two <code class="literal">int</code>s as
arguments.
</p></li><li class="listitem"><p>
You can compose pointcuts. For example,
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
<code class="literal">target(Point) && call(int *())</code>
</p></li><li class="listitem"><p>
<code class="literal">call(* *(..)) && (within(Line) || within(Point))</code>
</p></li><li class="listitem"><p>
<code class="literal">within(*) && execution(*.new(int))</code>
</p></li><li class="listitem"><p>
<code class="literal">
!this(Point) && call(int *(..))
</code>
</p></li></ol></div><p>
means (1) any call to an <code class="literal">int</code> method with no
arguments on an instance of <code class="literal">Point</code>,
regardless of its name, (2) any call to any method where the
call is made from the code in <code class="literal">Point</code>'s or
<code class="literal">Line</code>'s type declaration, (3) the execution of
any constructor taking exactly one <code class="literal">int</code>
argument, regardless of where the call is made from, and
(4) any method call to an <code class="literal">int</code> method when
the executing object is any type except <code class="literal">Point</code>.
</p></li><li class="listitem"><p>
You can select methods and constructors based on their
modifiers and on negations of modifiers. For example, you can
say:
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
<code class="literal">call(public * *(..))</code>
</p></li><li class="listitem"><p>
<code class="literal">execution(!static * *(..))</code>
</p></li><li class="listitem"><p>
<code class="literal"> execution(public !static * *(..))</code>
</p></li></ol></div><p>
which means (1) any call to a public method, (2) any
execution of a non-static method, and (3) any execution of a
public, non-static method.
</p></li><li class="listitem"><p>
Pointcuts can also deal with interfaces. For example, given the
interface </p><pre class="programlisting">
interface MyInterface { ... }
</pre><p>
the pointcut <code class="literal">call(* MyInterface.*(..))</code> picks
out any call to a method in <code class="literal">MyInterface</code>'s
signature -- that is, any method defined by
<code class="literal">MyInterface</code> or inherited by one of its a
supertypes.
</p></li></ul></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="call-vs-execution"></a>call vs. execution</h3></div></div></div><p>
When methods and constructors run, there are two interesting times
associated with them. That is when they are called, and when they
actually execute.
</p><p>
AspectJ exposes these times as call and execution join points,
respectively, and allows them to be picked out specifically by
<code class="literal">call</code> and <code class="literal">execution</code> pointcuts.
</p><p>
So what's the difference between these join points? Well, there are a
number of differences:
</p><p>
Firstly, the lexical pointcut declarations
<code class="literal">within</code> and <code class="literal">withincode</code> match
differently. At a call join point, the enclosing code is that of
the call site. This means that <code class="literal">call(void m())
&& withincode(void m())</code> will only capture
directly recursive calls, for example. At an execution join point,
however, the program is already executing the method, so the
enclosing code is the method itself: <code class="literal">execution(void m())
&& withincode(void m())</code> is the same as
<code class="literal">execution(void m())</code>.
</p><p>
Secondly, the call join point does not capture super calls to
non-static methods. This is because such super calls are different in
Java, since they don't behave via dynamic dispatch like other calls to
non-static methods.
</p><p>
The rule of thumb is that if you want to pick a join point that
runs when an actual piece of code runs (as is often the case for
tracing), use <code class="literal">execution</code>, but if you want to pick
one that runs when a particular <span class="emphasis"><em>signature</em></span> is
called (as is often the case for production aspects), use
<code class="literal">call</code>.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcut-composition"></a>Pointcut composition</h3></div></div></div><p>
Pointcuts are put together with the operators and (spelled
<code class="literal">&&</code>), or (spelled <code class="literal">||</code>),
and not (spelled <code class="literal">!</code>). This allows the creation
of very powerful pointcuts from the simple building blocks of
primitive pointcuts. This composition can be somewhat confusing
when used with primitive pointcuts like <code class="literal">cflow</code>
and <code class="literal">cflowbelow</code>. Here's an example:
</p><p>
<code class="literal">cflow(<em class="replaceable"><code>P</code></em>)</code> picks out
each join point in the control flow of the join points picked out
by <em class="replaceable"><code>P</code></em>. So, pictorially:
</p><pre class="programlisting">
P ---------------------
\
\ cflow of P
\
</pre><p>
What does <code class="literal">cflow(<em class="replaceable"><code>P</code></em>) &&
cflow(<em class="replaceable"><code>Q</code></em>)</code> pick out? Well, it
picks out each join point that is in both the control flow of
<em class="replaceable"><code>P</code></em> and in the control flow of
<em class="replaceable"><code>Q</code></em>. So...
</p><pre class="programlisting">
P ---------------------
\
\ cflow of P
\
\
\
Q -------------\-------
\ \
\ cflow of Q \ cflow(P) && cflow(Q)
\ \
</pre><p>
Note that <em class="replaceable"><code>P</code></em> and
<em class="replaceable"><code>Q</code></em> might not have any join points in
common... but their control flows might have join points in common.
</p><p>
But what does <code class="literal">cflow(<em class="replaceable"><code>P</code></em>
&& <em class="replaceable"><code>Q</code></em>)</code> mean? Well, it
means the control flow of those join points that are both picked
out by <em class="replaceable"><code>P</code></em> and picked out by
<em class="replaceable"><code>Q</code></em>.
</p><pre class="programlisting">
P && Q -------------------
\
\ cflow of (P && Q)
\
</pre><p>
and if there are <span class="emphasis"><em>no</em></span> join points that are both
picked by <em class="replaceable"><code>P</code></em> and picked out by
<em class="replaceable"><code>Q</code></em>, then there's no chance that there are
any join points in the control flow of
<code class="literal">(<em class="replaceable"><code>P</code></em> &&
<em class="replaceable"><code>Q</code></em>)</code>.
</p><p>
Here's some code that expresses this.
</p><pre class="programlisting">
public class Test {
public static void main(String[] args) {
foo();
}
static void foo() {
goo();
}
static void goo() {
System.out.println("hi");
}
}
aspect A {
pointcut fooPC(): execution(void Test.foo());
pointcut gooPC(): execution(void Test.goo());
pointcut printPC(): call(void java.io.PrintStream.println(String));
before(): cflow(fooPC()) && cflow(gooPC()) && printPC() && !within(A) {
System.out.println("should occur");
}
before(): cflow(fooPC() && gooPC()) && printPC() && !within(A) {
System.out.println("should not occur");
}
}
</pre><p>
The <code class="literal">!within(<em class="replaceable"><code>A</code></em>)</code>
pointcut above is required to avoid the <code class="literal">printPC</code>
pointcut applying to the <code class="literal">System.out.println</code>
call in the advice body. If this was not present a recursive call
would result as the pointcut would apply to its own advice.
(See <a class="xref" href="#pitfalls-infiniteLoops" title="Infinite loops">the section called “Infinite loops”</a> for more details.)
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcut-parameters"></a>Pointcut Parameters</h3></div></div></div><p>
Consider again the first pointcut definition in this chapter:
</p><pre class="programlisting">
pointcut setter(): target(Point) &&
(call(void setX(int)) ||
call(void setY(int)));
</pre><p>
As we've seen, this pointcut picks out each call to
<code class="literal">setX(int)</code> or <code class="literal">setY(int)</code>
methods where the target is an instance of
<code class="literal">Point</code>. The pointcut is given the name
<code class="literal">setters</code> and no parameters on the left-hand
side. An empty parameter list means that none of the context from
the join points is published from this pointcut. But consider
another version of version of this pointcut definition:
</p><pre class="programlisting">
pointcut setter(Point p): target(p) &&
(call(void setX(int)) ||
call(void setY(int)));
</pre><p>
This version picks out exactly the same join points. But in this
version, the pointcut has one parameter of type
<code class="literal">Point</code>. This means that any advice that uses this
pointcut has access to a <code class="literal">Point</code> from each join
point picked out by the pointcut. Inside the pointcut definition
this <code class="literal">Point</code> is named <code class="literal">p</code> is
available, and according to the right-hand side of the definition,
that <code class="literal">Point p</code> comes from the
<code class="literal">target</code> of each matched join point.
</p><p>
Here's another example that illustrates the flexible mechanism for
defining pointcut parameters:
</p><pre class="programlisting">
pointcut testEquality(Point p): target(Point) &&
args(p) &&
call(boolean equals(Object));
</pre><p>
This pointcut also has a parameter of type
<code class="literal">Point</code>. Similar to the
<code class="literal">setters</code> pointcut, this means that anyone using
this pointcut has access to a <code class="literal">Point</code> from each
join point. But in this case, looking at the right-hand side we
find that the object named in the parameters is not the target
<code class="literal">Point</code> object that receives the call; it's the
argument (also of type <code class="literal">Point</code>) passed to the
<code class="literal">equals</code> method when some other
<code class="literal">Point</code> is the target. If we wanted access to both
<code class="literal">Point</code>s, then the pointcut definition that would
expose target <code class="literal">Point p1</code> and argument
<code class="literal">Point p2</code> would be
</p><pre class="programlisting">
pointcut testEquality(Point p1, Point p2): target(p1) &&
args(p2) &&
call(boolean equals(Object));
</pre><p>
Let's look at another variation of the <code class="literal">setters</code> pointcut:
</p><pre class="programlisting">
pointcut setter(Point p, int newval): target(p) &&
args(newval) &&
(call(void setX(int)) ||
call(void setY(int)));
</pre><p>
In this case, a <code class="literal">Point</code> object and an
<code class="literal">int</code> value are exposed by the named
pointcut. Looking at the the right-hand side of the definition, we
find that the <code class="literal">Point</code> object is the target object,
and the <code class="literal">int</code> value is the called method's
argument.
</p><p>
The use of pointcut parameters is relatively flexible. The most
important rule is that all the pointcut parameters must be bound at
every join point picked out by the pointcut. So, for example, the
following pointcut definition will result in a compilation error:
</p><pre class="programlisting">
pointcut badPointcut(Point p1, Point p2):
(target(p1) && call(void setX(int))) ||
(target(p2) && call(void setY(int)));
</pre><p>
because <code class="literal">p1</code> is only bound when calling
<code class="literal">setX</code>, and <code class="literal">p2</code> is only bound
when calling <code class="literal">setY</code>, but the pointcut picks out
all of these join points and tries to bind both
<code class="literal">p1</code> and <code class="literal">p2</code>.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="example"></a>Example: <code class="literal">HandleLiveness</code></h3></div></div></div><p>
The example below consists of two object classes (plus an exception
class) and one aspect. Handle objects delegate their public,
non-static operations to their <code class="literal">Partner</code>
objects. The aspect <code class="literal">HandleLiveness</code> ensures that,
before the delegations, the partner exists and is alive, or else it
throws an exception.
</p><pre class="programlisting">
class Handle {
Partner partner = new Partner();
public void foo() { partner.foo(); }
public void bar(int x) { partner.bar(x); }
public static void main(String[] args) {
Handle h1 = new Handle();
h1.foo();
h1.bar(2);
}
}
class Partner {
boolean isAlive() { return true; }
void foo() { System.out.println("foo"); }
void bar(int x) { System.out.println("bar " + x); }
}
aspect HandleLiveness {
before(Handle handle): target(handle) && call(public * *(..)) {
if ( handle.partner == null || !handle.partner.isAlive() ) {
throw new DeadPartnerException();
}
}
}
class DeadPartnerException extends RuntimeException {}
</pre></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcut-best-practice"></a>Writing good pointcuts</h3></div></div></div><p>
During compilation, AspectJ processes pointcuts in order to try and optimize matching performance. Examining code and determining
if each join point matches (statically or dynamically) a given pointcut is a costly process.
(A dynamic match means the match cannot be fully determined from static analysis and a test will be placed in the code
to determine if there is an actual match when the code is running).
On first encountering a pointcut declaration, AspectJ will rewrite it into an optimal form for the matching process.
What does this mean? Basically pointcuts are rewritten in DNF (Disjunctive Normal Form) and the components of the pointcut
are sorted such that those components that are cheaper to evaluate are checked first. This means users do not have to worry
about understanding the performance of various pointcut designators and may supply them in any order in their
pointcut declarations.
</p><p>
However, AspectJ can only work with what it is told, and for optimal performance of matching the user should think
about what they are trying to achieve and narrow the search space for matches as much as they can in the definition.
Basically there are three kinds of pointcut designator: kinded, scoping and context:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
Kinded designators are those which select a particular kind of join point. For example: execution, get, set, call, handler
</li><li class="listitem">
Scoping designators are those which select a group of join points of interest (of probably many kinds). For example: within, withincode
</li><li class="listitem">
Contextual designators are those that match (and optionally bind) based on context. For example: this, target, @annotation
</li></ul></div><p>
A well written pointcut should
try and include at least the first two types (kinded and scoping), whilst the contextual designators may be included if wishing to
match based on join point context, or bind that context for use in the advice. Supplying either just a kinded designator or
just a contextual designator will work but could affect weaving performance (time and memory used)
due to all the extra processing and analysis.
Scoping designators are very fast to match, they can very quickly dismiss groups of join points that should not be further
processed - that is why a good pointcut should always include one if possible.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-advice"></a>Advice</h2></div></div></div><p>
Advice defines pieces of aspect implementation that execute at
well-defined points in the execution of the program. Those points can
be given either by named pointcuts (like the ones you've seen above)
or by anonymous pointcuts. Here is an example of an advice on a named
pointcut:
</p><pre class="programlisting">
pointcut setter(Point p1, int newval): target(p1) && args(newval)
(call(void setX(int) ||
call(void setY(int)));
before(Point p1, int newval): setter(p1, newval) {
System.out.println("About to set something in " + p1 +
" to the new value " + newval);
}
</pre><p>
And here is exactly the same example, but using an anonymous
pointcut:
</p><pre class="programlisting">
before(Point p1, int newval): target(p1) && args(newval)
(call(void setX(int)) ||
call(void setY(int))) {
System.out.println("About to set something in " + p1 +
" to the new value " + newval);
}
</pre><p>
Here are examples of the different advice:
</p><p>
This before advice runs just before the join points picked out by the
(anonymous) pointcut:
</p><pre class="programlisting">
before(Point p, int x): target(p) && args(x) && call(void setX(int)) {
if (!p.assertX(x)) return;
}
</pre><p>
This after advice runs just after each join point picked out by the
(anonymous) pointcut, regardless of whether it returns normally or throws
an exception:
</p><pre class="programlisting">
after(Point p, int x): target(p) && args(x) && call(void setX(int)) {
if (!p.assertX(x)) throw new PostConditionViolation();
}
</pre><p>
This after returning advice runs just after each join point picked
out by the (anonymous) pointcut, but only if it returns normally.
The return value can be accessed, and is named <code class="literal">x</code>
here. After the advice runs, the return value is returned:
</p><pre class="programlisting">
after(Point p) returning(int x): target(p) && call(int getX()) {
System.out.println("Returning int value " + x + " for p = " + p);
}
</pre><p>
This after throwing advice runs just after each join point picked out by
the (anonymous) pointcut, but only when it throws an exception of type
<code class="literal">Exception</code>. Here the exception value can be accessed
with the name <code class="literal">e</code>. The advice re-raises the exception
after it's done:
</p><pre class="programlisting">
after() throwing(Exception e): target(Point) && call(void setX(int)) {
System.out.println(e);
}
</pre><p>
This around advice traps the execution of the join point; it runs
<span class="emphasis"><em>instead</em></span> of the join point. The original action
associated with the join point can be invoked through the special
<code class="literal">proceed</code> call:
</p><pre class="programlisting">
void around(Point p, int x): target(p)
&& args(x)
&& call(void setX(int)) {
if (p.assertX(x)) proceed(p, x);
p.releaseResources();
}
</pre></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-interType"></a>Inter-type declarations</h2></div></div></div><p>
Aspects can declare members (fields, methods, and constructors) that
are owned by other types. These are called inter-type members.
Aspects can also declare that other types implement new interfaces or
extend a new class. Here are examples of some such inter-type
declarations:
</p><p>
This declares that each <code class="literal">Server</code> has a
<code class="literal">boolean</code> field named <code class="literal">disabled</code>,
initialized to <code class="literal">false</code>:
</p><pre class="programlisting">
private boolean Server.disabled = false;
</pre><p>
It is declared <code class="literal">private</code>, which means that it is
private <span class="emphasis"><em>to the aspect</em></span>: only code in the aspect
can see the field. And even if <code class="literal">Server</code> has
another private field named <code class="literal">disabled</code> (declared in
<code class="literal">Server</code> or in another aspect) there won't be a name
collision, since no reference to <code class="literal">disabled</code> will be
ambiguous.
</p><p>
This declares that each <code class="literal">Point</code> has an
<code class="literal">int</code> method named <code class="literal">getX</code> with no
arguments that returns whatever <code class="literal">this.x</code> is:
</p><pre class="programlisting">
public int Point.getX() { return this.x; }
</pre><p>
Inside the body, <code class="literal">this</code> is the
<code class="literal">Point</code> object currently executing. Because the
method is publically declared any code can call it, but if there is
some other <code class="literal">Point.getX()</code> declared there will be a
compile-time conflict.
</p><p>
This publically declares a two-argument constructor for
<code class="literal">Point</code>:
</p><pre class="programlisting">
public Point.new(int x, int y) { this.x = x; this.y = y; }
</pre><p>
</p><p>
This publicly declares that each <code class="literal">Point</code> has an
<code class="literal">int</code> field named <code class="literal">x</code>, initialized
to zero:
</p><pre class="programlisting">
public int Point.x = 0;
</pre><p>
Because this is publically declared, it is an error if
<code class="literal">Point</code> already has a field named
<code class="literal">x</code> (defined by <code class="literal">Point</code> or by
another aspect).
</p><p>
This declares that the <code class="literal">Point</code> class implements the
<code class="literal">Comparable</code> interface:
</p><pre class="programlisting">
declare parents: Point implements Comparable;
</pre><p>
Of course, this will be an error unless <code class="literal">Point</code>
defines the methods required by <code class="literal">Comparable</code>.
</p><p>
This declares that the <code class="literal">Point</code> class extends the
<code class="literal">GeometricObject</code> class.
</p><pre class="programlisting">
declare parents: Point extends GeometricObject;
</pre><p>
</p><p>
An aspect can have several inter-type declarations. For example, the
following declarations
</p><pre class="programlisting">
public String Point.name;
public void Point.setName(String name) { this.name = name; }
</pre><p>
publicly declare that Point has both a String field
<code class="literal">name</code> and a <code class="literal">void</code> method
<code class="literal">setName(String)</code> (which refers to the
<code class="literal">name</code> field declared by the aspect).
</p><p>
An inter-type member can only have one target type, but often you may
wish to declare the same member on more than one type. This can be
done by using an inter-type member in combination with a private
interface:
</p><pre class="programlisting">
aspect A {
private interface HasName {}
declare parents: (Point || Line || Square) implements HasName;
private String HasName.name;
public String HasName.getName() { return name; }
}
</pre><p>
This declares a marker interface <code class="literal">HasName</code>, and also declares that any
type that is either <code class="literal">Point</code>,
<code class="literal">Line</code>, or <code class="literal">Square</code> implements that
interface. It also privately declares that all <code class="literal">HasName</code>
object have a <code class="literal">String</code> field called
<code class="literal">name</code>, and publically declares that all
<code class="literal">HasName</code> objects have a <code class="literal">String</code>
method <code class="literal">getName()</code> (which refers to the privately
declared <code class="literal">name</code> field).
</p><p>
As you can see from the above example, an aspect can declare that
interfaces have fields and methods, even non-constant fields and
methods with bodies.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="inter-type-scope"></a>Inter-type Scope</h3></div></div></div><p>
AspectJ allows private and package-protected (default) inter-type declarations in
addition to public inter-type declarations. Private means private in
relation to the aspect, not necessarily the target type. So, if an
aspect makes a private inter-type declaration of a field
</p><pre class="programlisting">
private int Foo.x;
</pre><p>
Then code in the aspect can refer to <code class="literal">Foo</code>'s
<code class="literal">x</code> field, but nobody else can. Similarly, if an
aspect makes a package-protected introduction,
</p><pre class="programlisting">
int Foo.x;
</pre><p>
then everything in the aspect's package (which may or may not be
<code class="literal">Foo</code>'s package) can access <code class="literal">x</code>.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="example-pointassertions"></a>Example: <code class="literal">PointAssertions</code></h3></div></div></div><p>
The example below consists of one class and one aspect. The aspect
privately declares the assertion methods of
<code class="literal">Point</code>, <code class="literal">assertX</code> and
<code class="literal">assertY</code>. It also guards calls to
<code class="literal">setX</code> and <code class="literal">setY</code> with calls to
these assertion methods. The assertion methods are declared
privately because other parts of the program (including the code in
<code class="literal">Point</code>) have no business accessing the assert
methods. Only the code inside of the aspect can call those
methods.
</p><pre class="programlisting">
class Point {
int x, y;
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public static void main(String[] args) {
Point p = new Point();
p.setX(3); p.setY(333);
}
}
aspect PointAssertions {
private boolean Point.assertX(int x) {
return (x <= 100 && x >= 0);
}
private boolean Point.assertY(int y) {
return (y <= 100 && y >= 0);
}
before(Point p, int x): target(p) && args(x) && call(void setX(int)) {
if (!p.assertX(x)) {
System.out.println("Illegal value for x"); return;
}
}
before(Point p, int y): target(p) && args(y) && call(void setY(int)) {
if (!p.assertY(y)) {
System.out.println("Illegal value for y"); return;
}
}
}
</pre></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="language-thisJoinPoint"></a>thisJoinPoint</h2></div></div></div><p>
AspectJ provides a special reference variable,
<code class="literal">thisJoinPoint</code>, that contains reflective
information about the current join point for the advice to use. The
<code class="literal">thisJoinPoint</code> variable can only be used in the
context of advice, just like <code class="literal">this</code> can only be used
in the context of non-static methods and variable initializers. In
advice, <code class="literal">thisJoinPoint</code> is an object of type <a class="ulink" href="../api/org/aspectj/lang/JoinPoint.html" target="_top"><code class="literal">org.aspectj.lang.JoinPoint</code></a>.
</p><p>
One way to use it is simply to print it out. Like all Java objects,
<code class="literal">thisJoinPoint</code> has a <code class="literal">toString()</code>
method that makes quick-and-dirty tracing easy:
</p><pre class="programlisting">
aspect TraceNonStaticMethods {
before(Point p): target(p) && call(* *(..)) {
System.out.println("Entering " + thisJoinPoint + " in " + p);
}
}
</pre><p>
The type of <code class="literal">thisJoinPoint</code> includes a rich
reflective class hierarchy of signatures, and can be used to access
both static and dynamic information about join points such as the
arguments of the join point:
</p><pre class="programlisting">
thisJoinPoint.getArgs()
</pre><p>
In addition, it holds an object consisting of all the static
information about the join point such as corresponding line number
and static signature:
</p><pre class="programlisting">
thisJoinPoint.getStaticPart()
</pre><p>
If you only need the static information about the join point, you may
access the static part of the join point directly with the special
variable <code class="literal">thisJoinPointStaticPart</code>. Using
<code class="literal">thisJoinPointStaticPart</code> will avoid the run-time
creation of the join point object that may be necessary when using
<code class="literal">thisJoinPoint</code> directly.
</p><p>It is always the case that
</p><pre class="programlisting">
thisJoinPointStaticPart == thisJoinPoint.getStaticPart()
thisJoinPoint.getKind() == thisJoinPointStaticPart.getKind()
thisJoinPoint.getSignature() == thisJoinPointStaticPart.getSignature()
thisJoinPoint.getSourceLocation() == thisJoinPointStaticPart.getSourceLocation()
</pre><p>
One more reflective variable is available:
<code class="literal">thisEnclosingJoinPointStaticPart</code>. This, like
<code class="literal">thisJoinPointStaticPart</code>, only holds the static
part of a join point, but it is not the current but the enclosing
join point. So, for example, it is possible to print out the calling
source location (if available) with
</p><pre class="programlisting">
before() : execution (* *(..)) {
System.err.println(thisEnclosingJoinPointStaticPart.getSourceLocation())
}
</pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="examples"></a>Chapter 3. Examples</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#examples-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#examples-howto">Obtaining, Compiling and Running the Examples</a></span></dt><dt><span class="sect1"><a href="#examples-basic">Basic Techniques</a></span></dt><dd><dl><dt><span class="sect2"><a href="#examples-joinPoints">Join Points and <code class="literal">thisJoinPoint</code></a></span></dt><dt><span class="sect2"><a href="#examples-roles">Roles and Views</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-development">Development Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing-using-aspects">Tracing using aspects</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-production">Production Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#a-bean-aspect">A Bean Aspect</a></span></dt><dt><span class="sect2"><a href="#the-subject-observer-protocol">The Subject/Observer Protocol</a></span></dt><dt><span class="sect2"><a href="#a-simple-telecom-simulation">A Simple Telecom Simulation</a></span></dt></dl></dd><dt><span class="sect1"><a href="#examples-reusable">Reusable Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#tracing-using-aspects-revisited">Tracing using Aspects, Revisited</a></span></dt></dl></dd></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-intro"></a>Introduction</h2></div></div></div><p>
This chapter consists entirely of examples of AspectJ use.
</p><p>The examples can be grouped into four categories:</p><table border="0" summary="Simple list" class="simplelist"><tr><td><span class="bold"><strong>technique</strong></span></td><td>Examples which illustrate how to use one or more features of the
language. </td></tr><tr><td><span class="bold"><strong>development</strong></span></td><td>Examples of using AspectJ during the development phase of a
project. </td></tr><tr><td><span class="bold"><strong>production</strong></span></td><td>Examples of using AspectJ to provide functionality in an
application. </td></tr><tr><td><span class="bold"><strong>reusable</strong></span></td><td>Examples of reuse of aspects and pointcuts.</td></tr></table></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-howto"></a>Obtaining, Compiling and Running the Examples</h2></div></div></div><p>
The examples source code is part of the AspectJ distribution which may be
downloaded from the AspectJ project page ( <a class="ulink" href="http://eclipse.org/aspectj" target="_top">http://eclipse.org/aspectj</a> ).
</p><p>
Compiling most examples is straightforward. Go the
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples</code>
directory, and look for a <code class="filename">.lst</code> file in one of
the example subdirectories. Use the <code class="literal">-arglist</code>
option to <code class="literal">ajc</code> to compile the example. For
instance, to compile the telecom example with billing, type
</p><pre class="programlisting">
ajc -argfile telecom/billing.lst
</pre><p>
To run the examples, your classpath must include the AspectJ run-time
Java archive (<code class="literal">aspectjrt.jar</code>). You may either set the
<code class="literal">CLASSPATH</code> environment variable or use the
<code class="literal">-classpath</code> command line option to the Java
interpreter:
</p><pre class="programlisting">
(In Unix use a : in the CLASSPATH)
java -classpath ".:<em class="replaceable"><code>InstallDir</code></em>/lib/aspectjrt.jar" telecom.billingSimulation
</pre><pre class="programlisting">
(In Windows use a ; in the CLASSPATH)
java -classpath ".;<em class="replaceable"><code>InstallDir</code></em>/lib/aspectjrt.jar" telecom.billingSimulation
</pre></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-basic"></a>Basic Techniques</h2></div></div></div><p>
This section presents two basic techniques of using AspectJ, one each
from the two fundamental ways of capturing crosscutting concerns:
with dynamic join points and advice, and with static
introduction. Advice changes an application's behavior. Introduction
changes both an application's behavior and its structure.
</p><p>
The first example, <a class="xref" href="#examples-joinPoints" title="Join Points and thisJoinPoint">the section called “Join Points and <code class="literal">thisJoinPoint</code>”</a>, is about
gathering and using information about the join point that has
triggered some advice. The second example, <a class="xref" href="#examples-roles" title="Roles and Views">the section called “Roles and Views”</a>, concerns a crosscutting view of an
existing class hierarchy. </p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="examples-joinPoints"></a>Join Points and <code class="literal">thisJoinPoint</code></h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/tjp</code>.)
</p><p>
A join point is some point in the execution of a program together
with a view into the execution context when that point occurs. Join
points are picked out by pointcuts. When a program reaches a join
point, advice on that join point may run in addition to (or instead
of) the join point itself.
</p><p>
When using a pointcut that picks out join points of a single kind
by name, typicaly the the advice will know exactly what kind of
join point it is associated with. The pointcut may even publish
context about the join point. Here, for example, since the only
join points picked out by the pointcut are calls of a certain
method, we can get the target value and one of the argument values
of the method calls directly.
</p><pre class="programlisting">
before(Point p, int x): target(p)
&& args(x)
&& call(void setX(int)) {
if (!p.assertX(x)) {
System.out.println("Illegal value for x"); return;
}
}
</pre><p>
But sometimes the shape of the join point is not so clear. For
instance, suppose a complex application is being debugged, and we
want to trace when any method of some class is executed. The
pointcut
</p><pre class="programlisting">
pointcut execsInProblemClass(): within(ProblemClass)
&& execution(* *(..));
</pre><p>
will pick out each execution join point of every method defined
within <code class="classname">ProblemClass</code>. Since advice executes
at each join point picked out by the pointcut, we can reasonably
ask which join point was reached.
</p><p>
Information about the join point that was matched is available to
advice through the special variable
<code class="varname">thisJoinPoint</code>, of type <a class="ulink" href="../api/org/aspectj/lang/JoinPoint.html" target="_top"><code class="classname">org.aspectj.lang.JoinPoint</code></a>.
Through this object we can access information such as</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem">
the kind of join point that was matched
</li><li class="listitem">
the source location of the code associated with the join point
</li><li class="listitem">
normal, short and long string representations of the
current join point
</li><li class="listitem">
the actual argument values of the join point
</li><li class="listitem">
the signature of the member associated with the join point
</li><li class="listitem">the currently executing object</li><li class="listitem">the target object</li><li class="listitem">
an object encapsulating the static information about the join
point. This is also available through the special variable
<code class="varname">thisJoinPointStaticPart</code>.</li></ul></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm898"></a>The <code class="classname">Demo</code> class</h4></div></div></div><p>The class <code class="classname">tjp.Demo</code> in
<code class="filename">tjp/Demo.java</code> defines two methods
<code class="literal">foo</code> and <code class="literal">bar</code> with different
parameter lists and return types. Both are called, with suitable
arguments, by <code class="classname">Demo</code>'s
<code class="function">go</code> method which was invoked from within its
<code class="function">main</code> method.
</p><pre class="programlisting">
public class Demo {
static Demo d;
public static void main(String[] args){
new Demo().go();
}
void go(){
d = new Demo();
d.foo(1,d);
System.out.println(d.bar(new Integer(3)));
}
void foo(int i, Object o){
System.out.println("Demo.foo(" + i + ", " + o + ")\n");
}
String bar (Integer j){
System.out.println("Demo.bar(" + j + ")\n");
return "Demo.bar(" + j + ")";
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm910"></a>The <code class="literal">GetInfo</code> aspect</h4></div></div></div><p>
This aspect uses around advice to intercept the execution of
methods <code class="literal">foo</code> and <code class="literal">bar</code> in
<code class="classname">Demo</code>, and prints out information garnered
from <code class="literal">thisJoinPoint</code> to the console.
</p><pre class="programlisting">
aspect GetInfo {
static final void println(String s){ System.out.println(s); }
pointcut goCut(): cflow(this(Demo) && execution(void go()));
pointcut demoExecs(): within(Demo) && execution(* *(..));
Object around(): demoExecs() && !execution(* go()) && goCut() {
println("Intercepted message: " +
thisJoinPointStaticPart.getSignature().getName());
println("in class: " +
thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
printParameters(thisJoinPoint);
println("Running original method: \n" );
Object result = proceed();
println(" result: " + result );
return result;
}
static private void printParameters(JoinPoint jp) {
println("Arguments: " );
Object[] args = jp.getArgs();
String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes();
for (int i = 0; i < args.length; i++) {
println(" " + i + ". " + names[i] +
" : " + types[i].getName() +
" = " + args[i]);
}
}
}
</pre><div class="sect4"><div class="titlepage"><div><div><h5 class="title"><a name="idm919"></a>Defining the scope of a pointcut</h5></div></div></div><p>The pointcut <code class="function">goCut</code> is defined as
</p><pre class="programlisting">
cflow(this(Demo)) && execution(void go())
</pre><p>
so that only executions made in the control flow of
<code class="literal">Demo.go</code> are intercepted. The control flow
from the method <code class="literal">go</code> includes the execution of
<code class="literal">go</code> itself, so the definition of the around
advice includes <code class="literal">!execution(* go())</code> to
exclude it from the set of executions advised. </p></div><div class="sect4"><div class="titlepage"><div><div><h5 class="title"><a name="idm928"></a>Printing the class and method name</h5></div></div></div><p>
The name of the method and that method's defining class are
available as parts of the <a class="ulink" href="../api/org/aspectj/lang/Signature.html" target="_top">org.aspectj.lang.Signature</a>
object returned by calling <code class="literal">getSignature()</code> on
either <code class="literal">thisJoinPoint</code> or
<code class="literal">thisJoinPointStaticPart</code>.
</p></div><div class="sect4"><div class="titlepage"><div><div><h5 class="title"><a name="idm935"></a>Printing the parameters</h5></div></div></div><p>
The static portions of the parameter details, the name and
types of the parameters, can be accessed through the <a class="ulink" href="../api/org/aspectj/lang/reflect/CodeSignature.html" target="_top"><code class="literal">org.aspectj.lang.reflect.CodeSignature</code></a>
associated with the join point. All execution join points have code
signatures, so the cast to <code class="literal">CodeSignature</code>
cannot fail. </p><p>
The dynamic portions of the parameter details, the actual
values of the parameters, are accessed directly from the
execution join point object.
</p></div></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="examples-roles"></a>Roles and Views</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/introduction</code>.)
</p><p>
Like advice, inter-type declarations are members of an aspect. They
declare members that act as if they were defined on another class.
Unlike advice, inter-type declarations affect not only the behavior
of the application, but also the structural relationship between an
application's classes.
</p><p>
This is crucial: Publically affecting the class structure of an
application makes these modifications available to other components
of the application.
</p><p>
Aspects can declare inter-type
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem">fields</li><li class="listitem">methods</li><li class="listitem">constructors</li></ul></div><p>
and can also declare that target types
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem">implement new interfaces</li><li class="listitem">extend new classes</li></ul></div><p>
</p><p>
This example provides three illustrations of the use of inter-type
declarations to encapsulate roles or views of a class. The class
our aspect will be dealing with, <code class="classname">Point</code>, is a
simple class with rectangular and polar coordinates. Our inter-type
declarations will make the class <code class="classname">Point</code>, in
turn, cloneable, hashable, and comparable. These facilities are
provided by AspectJ without having to modify the code for the class
<code class="classname">Point</code>.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm961"></a>The <code class="classname">Point</code> class</h4></div></div></div><p>The <code class="classname">Point</code> class defines geometric points
whose interface includes polar and rectangular coordinates, plus some
simple operations to relocate points. <code class="classname">Point</code>'s
implementation has attributes for both its polar and rectangular
coordinates, plus flags to indicate which currently reflect the
position of the point. Some operations cause the polar coordinates to
be updated from the rectangular, and some have the opposite effect.
This implementation, which is in intended to give the minimum number
of conversions between coordinate systems, has the property that not
all the attributes stored in a <code class="classname">Point</code> object
are necessary to give a canonical representation such as might be
used for storing, comparing, cloning or making hash codes from
points. Thus the aspects, though simple, are not totally trivial.
</p><p>
The diagram below gives an overview of the aspects and their
interaction with the class <code class="classname">Point</code>.</p><p>
<span class="inlinemediaobject"><img src="aspects.gif"></span>
</p><p></p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm975"></a>The <code class="classname">CloneablePoint</code> aspect</h4></div></div></div><p>
This first aspect is responsible for
<code class="classname">Point</code>'s implementation of the
<code class="classname">Cloneable</code> interface. It declares that
<code class="literal">Point implements Cloneable</code> with a
<code class="literal">declare parents</code> form, and also publically
declares a specialized <code class="literal">Point</code>'s
<code class="literal">clone()</code> method. In Java, all objects inherit
the method <code class="literal">clone</code> from the class
<code class="classname">Object</code>, but an object is not cloneable
unless its class also implements the interface
<code class="classname">Cloneable</code>. In addition, classes
frequently have requirements over and above the simple
bit-for-bit copying that <code class="literal">Object.clone</code> does. In
our case, we want to update a <code class="classname">Point</code>'s
coordinate systems before we actually clone the
<code class="classname">Point</code>. So our aspect makes sure that
<code class="literal">Point</code> overrides
<code class="literal">Object.clone</code> with a new method that does what
we want.
</p><p>
We also define a test <code class="literal">main</code> method in the
aspect for convenience.
</p><pre class="programlisting">
public aspect CloneablePoint {
declare parents: Point implements Cloneable;
public Object Point.clone() throws CloneNotSupportedException {
// we choose to bring all fields up to date before cloning.
makeRectangular();
makePolar();
return super.clone();
}
public static void main(String[] args){
Point p1 = new Point();
Point p2 = null;
p1.setPolar(Math.PI, 1.0);
try {
p2 = (Point)p1.clone();
} catch (CloneNotSupportedException e) {}
System.out.println("p1 =" + p1 );
System.out.println("p2 =" + p2 );
p1.rotate(Math.PI / -2);
System.out.println("p1 =" + p1 );
System.out.println("p2 =" + p2 );
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm996"></a>The <code class="classname">ComparablePoint</code> aspect</h4></div></div></div><p>
<code class="classname">ComparablePoint</code> is responsible for
<code class="literal">Point</code>'s implementation of the
<code class="literal">Comparable</code> interface. </p><p>
The interface <code class="classname">Comparable</code> defines the
single method <code class="literal">compareTo</code> which can be use to define
a natural ordering relation among the objects of a class that
implement it.
</p><p>
<code class="classname">ComparablePoint</code> uses <code class="literal">declare
parents</code> to declare that <code class="literal">Point implements
Comparable</code>, and also publically declares the
appropriate <code class="literal">compareTo(Object)</code> method: A
<code class="classname">Point</code> <code class="literal">p1</code> is said to be
less than another <code class="classname">Point</code><code class="literal">
p2</code> if <code class="literal">p1</code> is closer to the
origin.
</p><p>
We also define a test <code class="literal">main</code> method in the
aspect for convenience.
</p><pre class="programlisting">
public aspect ComparablePoint {
declare parents: Point implements Comparable;
public int Point.compareTo(Object o) {
return (int) (this.getRho() - ((Point)o).getRho());
}
public static void main(String[] args){
Point p1 = new Point();
Point p2 = new Point();
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.setRectangular(2,5);
p2.setRectangular(2,5);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p2.setRectangular(3,6);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.setPolar(Math.PI, 4);
p2.setPolar(Math.PI, 4);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.rotate(Math.PI / 4.0);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.offset(1,1);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1019"></a>The <code class="classname">HashablePoint</code> aspect</h4></div></div></div><p>
Our third aspect is responsible for <code class="literal">Point</code>'s
overriding of <code class="literal">Object</code>'s
<code class="literal">equals</code> and <code class="literal">hashCode</code> methods
in order to make <code class="literal">Point</code>s hashable.
</p><p>
The method <code class="literal">Object.hashCode</code> returns an
integer, suitable for use as a hash table key. It is not required
that two objects which are not equal (according to the
<code class="literal">equals</code> method) return different integer
results from <code class="literal">hashCode</code> but it can
improve performance when the integer is used as a key into a
data structure. However, any two objects which are equal
must return the same integer value from a call to
<code class="literal">hashCode</code>. Since the default implementation
of <code class="literal">Object.equals</code> returns <code class="literal">true</code>
only when two objects are identical, we need to redefine both
<code class="function">equals</code> and <code class="function">hashCode</code> to work
correctly with objects of type <code class="classname">Point</code>. For
example, we want two <code class="classname">Point</code> objects to test
equal when they have the same <code class="literal">x</code> and
<code class="literal">y</code> values, or the same <code class="literal">rho</code> and
<code class="literal">theta</code> values, not just when they refer to the same
object. We do this by overriding the methods
<code class="literal">equals</code> and <code class="literal">hashCode</code> in the
class <code class="classname">Point</code>.
</p><p>
So <code class="classname">HashablePoint</code> declares
<code class="literal">Point</code>'s <code class="literal">hashCode</code> and
<code class="literal">equals</code> methods, using
<code class="classname">Point</code>'s rectangular coordinates to
generate a hash code and to test for equality. The
<code class="literal">x</code> and <code class="literal">y</code> coordinates are
obtained using the appropriate get methods, which ensure the
rectangular coordinates are up-to-date before returning their
values.
</p><p>
And again, we supply a <code class="literal">main</code> method in the
aspect for testing.
</p><pre class="programlisting">
public aspect HashablePoint {
public int Point.hashCode() {
return (int) (getX() + getY() % Integer.MAX_VALUE);
}
public boolean Point.equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof Point)) { return false; }
Point other = (Point)o;
return (getX() == other.getX()) && (getY() == other.getY());
}
public static void main(String[] args) {
Hashtable h = new Hashtable();
Point p1 = new Point();
p1.setRectangular(10, 10);
Point p2 = new Point();
p2.setRectangular(10, 10);
System.out.println("p1 = " + p1);
System.out.println("p2 = " + p2);
System.out.println("p1.hashCode() = " + p1.hashCode());
System.out.println("p2.hashCode() = " + p2.hashCode());
h.put(p1, "P1");
System.out.println("Got: " + h.get(p2));
}
}
</pre></div></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-development"></a>Development Aspects</h2></div></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="tracing-using-aspects"></a>Tracing using aspects</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/tracing</code>.)
</p><p>
Writing a class that provides tracing functionality is easy: a
couple of functions, a boolean flag for turning tracing on and
off, a choice for an output stream, maybe some code for
formatting the output -- these are all elements that
<code class="classname">Trace</code> classes have been known to
have. <code class="classname">Trace</code> classes may be highly
sophisticated, too, if the task of tracing the execution of a
program demands it.
</p><p>
But developing the support for tracing is just one part of the
effort of inserting tracing into a program, and, most likely, not
the biggest part. The other part of the effort is calling the
tracing functions at appropriate times. In large systems, this
interaction with the tracing support can be overwhelming. Plus,
tracing is one of those things that slows the system down, so
these calls should often be pulled out of the system before the
product is shipped. For these reasons, it is not unusual for
developers to write ad-hoc scripting programs that rewrite the
source code by inserting/deleting trace calls before and after
the method bodies.
</p><p>
AspectJ can be used for some of these tracing concerns in a less
ad-hoc way. Tracing can be seen as a concern that crosscuts the
entire system and as such is amenable to encapsulation in an
aspect. In addition, it is fairly independent of what the system
is doing. Therefore tracing is one of those kind of system
aspects that can potentially be plugged in and unplugged without
any side-effects in the basic functionality of the system.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1069"></a>An Example Application</h4></div></div></div><p>
Throughout this example we will use a simple application that
contains only four classes. The application is about shapes. The
<code class="classname">TwoDShape</code> class is the root of the shape
hierarchy:
</p><pre class="programlisting">
public abstract class TwoDShape {
protected double x, y;
protected TwoDShape(double x, double y) {
this.x = x; this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public double distance(TwoDShape s) {
double dx = Math.abs(s.getX() - x);
double dy = Math.abs(s.getY() - y);
return Math.sqrt(dx*dx + dy*dy);
}
public abstract double perimeter();
public abstract double area();
public String toString() {
return (" @ (" + String.valueOf(x) + ", " + String.valueOf(y) + ") ");
}
}
</pre><p>
<code class="classname">TwoDShape</code> has two subclasses,
<code class="classname">Circle</code> and <code class="classname">Square</code>:
</p><pre class="programlisting">
public class Circle extends TwoDShape {
protected double r;
public Circle(double x, double y, double r) {
super(x, y); this.r = r;
}
public Circle(double x, double y) { this( x, y, 1.0); }
public Circle(double r) { this(0.0, 0.0, r); }
public Circle() { this(0.0, 0.0, 1.0); }
public double perimeter() {
return 2 * Math.PI * r;
}
public double area() {
return Math.PI * r*r;
}
public String toString() {
return ("Circle radius = " + String.valueOf(r) + super.toString());
}
}
</pre><pre class="programlisting">
public class Square extends TwoDShape {
protected double s; // side
public Square(double x, double y, double s) {
super(x, y); this.s = s;
}
public Square(double x, double y) { this( x, y, 1.0); }
public Square(double s) { this(0.0, 0.0, s); }
public Square() { this(0.0, 0.0, 1.0); }
public double perimeter() {
return 4 * s;
}
public double area() {
return s*s;
}
public String toString() {
return ("Square side = " + String.valueOf(s) + super.toString());
}
}
</pre><p>
To run this application, compile the classes. You can do it with or
without ajc, the AspectJ compiler. If you've installed AspectJ, go
to the directory
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples</code>
and type:
</p><pre class="programlisting">
ajc -argfile tracing/notrace.lst
</pre><p>To run the program, type</p><pre class="programlisting">
java tracing.ExampleMain
</pre><p>(we don't need anything special on the classpath since this is pure
Java code). You should see the following output:</p><pre class="programlisting">
c1.perimeter() = 12.566370614359172
c1.area() = 12.566370614359172
s1.perimeter() = 4.0
s1.area() = 1.0
c2.distance(c1) = 4.242640687119285
s1.distance(c1) = 2.23606797749979
s1.toString(): Square side = 1.0 @ (1.0, 2.0)
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1088"></a>Tracing—Version 1</h4></div></div></div><p>
In a first attempt to insert tracing in this application, we will
start by writing a <code class="classname">Trace</code> class that is
exactly what we would write if we didn't have aspects. The
implementation is in <code class="filename">version1/Trace.java</code>. Its
public interface is:
</p><pre class="programlisting">
public class Trace {
public static int TRACELEVEL = 0;
public static void initStream(PrintStream s) {...}
public static void traceEntry(String str) {...}
public static void traceExit(String str) {...}
}
</pre><p>
If we didn't have AspectJ, we would have to insert calls to
<code class="literal">traceEntry</code> and <code class="literal">traceExit</code> in
all methods and constructors we wanted to trace, and to initialize
<code class="literal">TRACELEVEL</code> and the stream. If we wanted to trace
all the methods and constructors in our example, that would amount
to around 40 calls, and we would hope we had not forgotten any
method. But we can do that more consistently and reliably with the
following aspect (found in
<code class="filename">version1/TraceMyClasses.java</code>):
</p><pre class="programlisting">
aspect TraceMyClasses {
pointcut myClass(): within(TwoDShape) || within(Circle) || within(Square);
pointcut myConstructor(): myClass() && execution(new(..));
pointcut myMethod(): myClass() && execution(* *(..));
before (): myConstructor() {
Trace.traceEntry("" + thisJoinPointStaticPart.getSignature());
}
after(): myConstructor() {
Trace.traceExit("" + thisJoinPointStaticPart.getSignature());
}
before (): myMethod() {
Trace.traceEntry("" + thisJoinPointStaticPart.getSignature());
}
after(): myMethod() {
Trace.traceExit("" + thisJoinPointStaticPart.getSignature());
}
}</pre><p>
This aspect performs the tracing calls at appropriate
times. According to this aspect, tracing is performed at the
entrance and exit of every method and constructor defined within
the shape hierarchy.
</p><p>
What is printed at before and after each of the traced join points
is the signature of the method executing. Since the signature is
static information, we can get it through
<code class="literal">thisJoinPointStaticPart</code>.
</p><p>
To run this version of tracing, go to the directory
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples</code>
and type:
</p><pre class="programlisting">
ajc -argfile tracing/tracev1.lst
</pre><p>
Running the main method of
<code class="classname">tracing.version1.TraceMyClasses</code> should produce
the output:
</p><pre class="programlisting">
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Circle(double, double, double)
<-- tracing.Circle(double, double, double)
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Circle(double, double, double)
<-- tracing.Circle(double, double, double)
--> tracing.Circle(double)
<-- tracing.Circle(double)
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Square(double, double, double)
<-- tracing.Square(double, double, double)
--> tracing.Square(double, double)
<-- tracing.Square(double, double)
--> double tracing.Circle.perimeter()
<-- double tracing.Circle.perimeter()
c1.perimeter() = 12.566370614359172
--> double tracing.Circle.area()
<-- double tracing.Circle.area()
c1.area() = 12.566370614359172
--> double tracing.Square.perimeter()
<-- double tracing.Square.perimeter()
s1.perimeter() = 4.0
--> double tracing.Square.area()
<-- double tracing.Square.area()
s1.area() = 1.0
--> double tracing.TwoDShape.distance(TwoDShape)
--> double tracing.TwoDShape.getX()
<-- double tracing.TwoDShape.getX()
--> double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.distance(TwoDShape)
c2.distance(c1) = 4.242640687119285
--> double tracing.TwoDShape.distance(TwoDShape)
--> double tracing.TwoDShape.getX()
<-- double tracing.TwoDShape.getX()
--> double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.distance(TwoDShape)
s1.distance(c1) = 2.23606797749979
--> String tracing.Square.toString()
--> String tracing.TwoDShape.toString()
<-- String tracing.TwoDShape.toString()
<-- String tracing.Square.toString()
s1.toString(): Square side = 1.0 @ (1.0, 2.0)
</pre><p>
When <code class="filename">TraceMyClasses.java</code> is not provided to
<span class="command"><strong>ajc</strong></span>, the aspect does not have any affect on the
system and the tracing is unplugged.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1113"></a>Tracing—Version 2</h4></div></div></div><p>
Another way to accomplish the same thing would be to write a
reusable tracing aspect that can be used not only for these
application classes, but for any class. One way to do this is to
merge the tracing functionality of
<code class="literal">Trace—version1</code> with the crosscutting
support of <code class="literal">TraceMyClasses—version1</code>. We end
up with a <code class="literal">Trace</code> aspect (found in
<code class="filename">version2/Trace.java</code>) with the following public
interface
</p><pre class="programlisting">
abstract aspect Trace {
public static int TRACELEVEL = 2;
public static void initStream(PrintStream s) {...}
protected static void traceEntry(String str) {...}
protected static void traceExit(String str) {...}
abstract pointcut myClass();
}
</pre><p>
In order to use it, we need to define our own subclass that knows
about our application classes, in
<code class="filename">version2/TraceMyClasses.java</code>:
</p><pre class="programlisting">
public aspect TraceMyClasses extends Trace {
pointcut myClass(): within(TwoDShape) || within(Circle) || within(Square);
public static void main(String[] args) {
Trace.TRACELEVEL = 2;
Trace.initStream(System.err);
ExampleMain.main(args);
}
}
</pre><p>
Notice that we've simply made the pointcut
<code class="literal">classes</code>, that was an abstract pointcut in the
super-aspect, concrete. To run this version of tracing, go to the
directory <code class="filename">examples</code> and type:
</p><pre class="programlisting">
ajc -argfile tracing/tracev2.lst
</pre><p>
The file tracev2.lst lists the application classes as well as this
version of the files Trace.java and TraceMyClasses.java. Running
the main method of
<code class="classname">tracing.version2.TraceMyClasses</code> should
output exactly the same trace information as that from version 1.
</p><p>
The entire implementation of the new <code class="classname">Trace</code>
class is:
</p><pre class="programlisting">
abstract aspect Trace {
// implementation part
public static int TRACELEVEL = 2;
protected static PrintStream stream = System.err;
protected static int callDepth = 0;
public static void initStream(PrintStream s) {
stream = s;
}
protected static void traceEntry(String str) {
if (TRACELEVEL == 0) return;
if (TRACELEVEL == 2) callDepth++;
printEntering(str);
}
protected static void traceExit(String str) {
if (TRACELEVEL == 0) return;
printExiting(str);
if (TRACELEVEL == 2) callDepth--;
}
private static void printEntering(String str) {
printIndent();
stream.println("--> " + str);
}
private static void printExiting(String str) {
printIndent();
stream.println("<-- " + str);
}
private static void printIndent() {
for (int i = 0; i < callDepth; i++)
stream.print(" ");
}
// protocol part
abstract pointcut myClass();
pointcut myConstructor(): myClass() && execution(new(..));
pointcut myMethod(): myClass() && execution(* *(..));
before(): myConstructor() {
traceEntry("" + thisJoinPointStaticPart.getSignature());
}
after(): myConstructor() {
traceExit("" + thisJoinPointStaticPart.getSignature());
}
before(): myMethod() {
traceEntry("" + thisJoinPointStaticPart.getSignature());
}
after(): myMethod() {
traceExit("" + thisJoinPointStaticPart.getSignature());
}
}
</pre><p>
This version differs from version 1 in several subtle ways. The
first thing to notice is that this <code class="classname">Trace</code>
class merges the functional part of tracing with the crosscutting
of the tracing calls. That is, in version 1, there was a sharp
separation between the tracing support (the class
<code class="classname">Trace</code>) and the crosscutting usage of it (by
the class <code class="classname">TraceMyClasses</code>). In this version
those two things are merged. That's why the description of this
class explicitly says that "Trace messages are printed before and
after constructors and methods are," which is what we wanted in the
first place. That is, the placement of the calls, in this version,
is established by the aspect class itself, leaving less opportunity
for misplacing calls.</p><p>
A consequence of this is that there is no need for providing
<code class="literal">traceEntry</code> and <code class="literal">traceExit</code> as
public operations of this class. You can see that they were
classified as protected. They are supposed to be internal
implementation details of the advice.
</p><p>
The key piece of this aspect is the abstract pointcut classes that
serves as the base for the definition of the pointcuts constructors
and methods. Even though <code class="classname">classes</code> is
abstract, and therefore no concrete classes are mentioned, we can
put advice on it, as well as on the pointcuts that are based on
it. The idea is "we don't know exactly what the pointcut will be,
but when we do, here's what we want to do with it." In some ways,
abstract pointcuts are similar to abstract methods. Abstract
methods don't provide the implementation, but you know that the
concrete subclasses will, so you can invoke those methods.
</p></div></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-production"></a>Production Aspects</h2></div></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="a-bean-aspect"></a>A Bean Aspect</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/bean</code>.)
</p><p>
This example examines an aspect that makes Point objects into
Java beans with bound properties.
</p><p>
Java beans are reusable software components that can be visually
manipulated in a builder tool. The requirements for an object to be
a bean are few. Beans must define a no-argument constructor and
must be either <code class="classname">Serializable</code> or
<code class="classname">Externalizable</code>. Any properties of the object
that are to be treated as bean properties should be indicated by
the presence of appropriate <code class="literal">get</code> and
<code class="literal">set</code> methods whose names are
<code class="literal">get</code><span class="emphasis"><em>property</em></span> and
<code class="literal">set </code><span class="emphasis"><em>property</em></span> where
<span class="emphasis"><em>property</em></span> is the name of a field in the bean
class. Some bean properties, known as bound properties, fire events
whenever their values change so that any registered listeners (such
as, other beans) will be informed of those changes. Making a bound
property involves keeping a list of registered listeners, and
creating and dispatching event objects in methods that change the
property values, such as set<span class="emphasis"><em>property</em></span>
methods.
</p><p>
<code class="classname">Point</code> is a simple class representing points
with rectangular coordinates. <code class="classname">Point</code> does not
know anything about being a bean: there are set methods for
<code class="literal">x</code> and <code class="literal">y</code> but they do not fire
events, and the class is not serializable. Bound is an aspect that
makes <code class="classname">Point</code> a serializable class and makes
its <code class="literal">get</code> and <code class="literal">set</code> methods
support the bound property protocol.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1169"></a>The <code class="classname">Point</code> class</h4></div></div></div><p>
The <code class="classname">Point</code> class is a very simple class with
trivial getters and setters, and a simple vector offset method.
</p><pre class="programlisting">
class Point {
protected int x = 0;
protected int y = 0;
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setRectangular(int newX, int newY) {
setX(newX);
setY(newY);
}
public void setX(int newX) {
x = newX;
}
public void setY(int newY) {
y = newY;
}
public void offset(int deltaX, int deltaY) {
setRectangular(x + deltaX, y + deltaY);
}
public String toString() {
return "(" + getX() + ", " + getY() + ")" ;
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1175"></a>The <code class="classname">BoundPoint</code> aspect</h4></div></div></div><p>
The <code class="classname">BoundPoint</code> aspect is responsible for
<code class="literal">Point</code>'s "beanness". The first thing it does is
privately declare that each <code class="literal">Point</code> has a
<code class="literal">support</code> field that holds reference to an
instance of <code class="classname">PropertyChangeSupport</code>.
</p><pre class="programlisting">
private PropertyChangeSupport Point.support = new PropertyChangeSupport(this);
</pre><p>
The property change support object must be constructed with a
reference to the bean for which it is providing support, so it is
initialized by passing it <code class="literal">this</code>, an instance of
<code class="classname">Point</code>. Since the <code class="literal">support</code>
field is private declared in the aspect, only the code in the
aspect can refer to it.
</p><p>
The aspect also declares <code class="literal">Point</code>'s methods for
registering and managing listeners for property change events,
which delegate the work to the property change support object:
</p><pre class="programlisting">
public void Point.addPropertyChangeListener(PropertyChangeListener listener){
support.addPropertyChangeListener(listener);
}
public void Point.addPropertyChangeListener(String propertyName,
PropertyChangeListener listener){
support.addPropertyChangeListener(propertyName, listener);
}
public void Point.removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
support.removePropertyChangeListener(propertyName, listener);
}
public void Point.removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
public void Point.hasListeners(String propertyName) {
support.hasListeners(propertyName);
}
</pre><p>
</p><p>
The aspect is also responsible for making sure
<code class="classname">Point</code> implements the
<code class="classname">Serializable</code> interface:
</p><pre class="programlisting">
declare parents: Point implements Serializable;
</pre><p>
Implementing this interface in Java does not require any methods to
be implemented. Serialization for <code class="classname">Point</code>
objects is provided by the default serialization method.
</p><p>
The <code class="function">setters</code> pointcut picks out calls to the
<code class="literal">Point</code>'s <code class="literal">set</code> methods: any
method whose name begins with "<code class="literal">set</code>" and takes
one parameter. The around advice on <code class="literal">setters()</code>
stores the values of the <code class="literal">X</code> and
<code class="literal">Y</code> properties, calls the original
<code class="literal">set</code> method and then fires the appropriate
property change event according to which set method was
called.
</p><pre class="programlisting">
aspect BoundPoint {
private PropertyChangeSupport Point.support = new PropertyChangeSupport(this);
public void Point.addPropertyChangeListener(PropertyChangeListener listener){
support.addPropertyChangeListener(listener);
}
public void Point.addPropertyChangeListener(String propertyName,
PropertyChangeListener listener){
support.addPropertyChangeListener(propertyName, listener);
}
public void Point.removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
support.removePropertyChangeListener(propertyName, listener);
}
public void Point.removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
public void Point.hasListeners(String propertyName) {
support.hasListeners(propertyName);
}
declare parents: Point implements Serializable;
pointcut setter(Point p): call(void Point.set*(*)) && target(p);
void around(Point p): setter(p) {
String propertyName =
thisJoinPointStaticPart.getSignature().getName().substring("set".length());
int oldX = p.getX();
int oldY = p.getY();
proceed(p);
if (propertyName.equals("X")){
firePropertyChange(p, propertyName, oldX, p.getX());
} else {
firePropertyChange(p, propertyName, oldY, p.getY());
}
}
void firePropertyChange(Point p,
String property,
double oldval,
double newval) {
p.support.firePropertyChange(property,
new Double(oldval),
new Double(newval));
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1206"></a>The Test Program</h4></div></div></div><p>
The test program registers itself as a property change listener to
a <code class="literal">Point</code> object that it creates and then performs
simple manipulation of that point: calling its set methods and the
offset method. Then it serializes the point and writes it to a file
and then reads it back. The result of saving and restoring the
point is that a new point is created.
</p><pre class="programlisting">
class Demo implements PropertyChangeListener {
static final String fileName = "test.tmp";
public void propertyChange(PropertyChangeEvent e){
System.out.println("Property " + e.getPropertyName() + " changed from " +
e.getOldValue() + " to " + e.getNewValue() );
}
public static void main(String[] args){
Point p1 = new Point();
p1.addPropertyChangeListener(new Demo());
System.out.println("p1 =" + p1);
p1.setRectangular(5,2);
System.out.println("p1 =" + p1);
p1.setX( 6 );
p1.setY( 3 );
System.out.println("p1 =" + p1);
p1.offset(6,4);
System.out.println("p1 =" + p1);
save(p1, fileName);
Point p2 = (Point) restore(fileName);
System.out.println("Had: " + p1);
System.out.println("Got: " + p2);
}
...
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1211"></a>Compiling and Running the Example</h4></div></div></div><p>
To compile and run this example, go to the examples directory and type:
</p><pre class="programlisting">
ajc -argfile bean/files.lst
java bean.Demo
</pre></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="the-subject-observer-protocol"></a>The Subject/Observer Protocol</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/observer</code>.)
</p><p>
This demo illustrates how the Subject/Observer design pattern can be
coded with aspects.
</p><p>
The demo consists of the following: A colored label is a
renderable object that has a color that cycles through a set of
colors, and a number that records the number of cycles it has been
through. A button is an action item that records when it is
clicked.
</p><p>
With these two kinds of objects, we can build up a Subject/Observer
relationship in which colored labels observe the clicks of buttons;
that is, where colored labels are the observers and buttons are the
subjects.
</p><p>
The demo is designed and implemented using the Subject/Observer
design pattern. The remainder of this example explains the classes
and aspects of this demo, and tells you how to run it.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1224"></a>Generic Components</h4></div></div></div><p>
The generic parts of the protocol are the interfaces
<code class="classname">Subject</code> and <code class="classname">Observer</code>,
and the abstract aspect
<code class="classname">SubjectObserverProtocol</code>. The
<code class="classname">Subject</code> interface is simple, containing
methods to add, remove, and view <code class="classname">Observer</code>
objects, and a method for getting data about state changes:
</p><pre class="programlisting">
interface Subject {
void addObserver(Observer obs);
void removeObserver(Observer obs);
Vector getObservers();
Object getData();
}
</pre><p>
The <code class="classname">Observer</code> interface is just as simple,
with methods to set and get <code class="classname">Subject</code> objects,
and a method to call when the subject gets updated.
</p><pre class="programlisting">
interface Observer {
void setSubject(Subject s);
Subject getSubject();
void update();
}
</pre><p>
The <code class="classname">SubjectObserverProtocol</code> aspect contains
within it all of the generic parts of the protocol, namely, how to
fire the <code class="classname">Observer</code> objects' update methods
when some state changes in a subject.
</p><pre class="programlisting">
abstract aspect SubjectObserverProtocol {
abstract pointcut stateChanges(Subject s);
after(Subject s): stateChanges(s) {
for (int i = 0; i < s.getObservers().size(); i++) {
((Observer)s.getObservers().elementAt(i)).update();
}
}
private Vector Subject.observers = new Vector();
public void Subject.addObserver(Observer obs) {
observers.addElement(obs);
obs.setSubject(this);
}
public void Subject.removeObserver(Observer obs) {
observers.removeElement(obs);
obs.setSubject(null);
}
public Vector Subject.getObservers() { return observers; }
private Subject Observer.subject = null;
public void Observer.setSubject(Subject s) { subject = s; }
public Subject Observer.getSubject() { return subject; }
}
</pre><p>
Note that this aspect does three things. It define an abstract
pointcut that extending aspects can override. It defines advice
that should run after the join points of the pointcut. And it
declares an inter-tpye field and two inter-type methods so that
each <code class="literal">Observer</code> can hold onto its <code class="literal">Subject</code>.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1244"></a>Application Classes</h4></div></div></div><p>
<code class="classname">Button</code> objects extend
<code class="classname">java.awt.Button</code>, and all they do is make
sure the <code class="literal">void click()</code> method is called whenever
a button is clicked.
</p><pre class="programlisting">
class Button extends java.awt.Button {
static final Color defaultBackgroundColor = Color.gray;
static final Color defaultForegroundColor = Color.black;
static final String defaultText = "cycle color";
Button(Display display) {
super();
setLabel(defaultText);
setBackground(defaultBackgroundColor);
setForeground(defaultForegroundColor);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Button.this.click();
}
});
display.addToFrame(this);
}
public void click() {}
}
</pre><p>
Note that this class knows nothing about being a Subject.
</p><p>
ColorLabel objects are labels that support the void colorCycle()
method. Again, they know nothing about being an observer.
</p><pre class="programlisting">
class ColorLabel extends Label {
ColorLabel(Display display) {
super();
display.addToFrame(this);
}
final static Color[] colors = {Color.red, Color.blue,
Color.green, Color.magenta};
private int colorIndex = 0;
private int cycleCount = 0;
void colorCycle() {
cycleCount++;
colorIndex = (colorIndex + 1) % colors.length;
setBackground(colors[colorIndex]);
setText("" + cycleCount);
}
}
</pre><p>
Finally, the <code class="classname">SubjectObserverProtocolImpl</code>
implements the subject/observer protocol, with
<code class="classname">Button</code> objects as subjects and
<code class="classname">ColorLabel</code> objects as observers:
</p><pre class="programlisting">
package observer;
import java.util.Vector;
aspect SubjectObserverProtocolImpl extends SubjectObserverProtocol {
declare parents: Button implements Subject;
public Object Button.getData() { return this; }
declare parents: ColorLabel implements Observer;
public void ColorLabel.update() {
colorCycle();
}
pointcut stateChanges(Subject s):
target(s) &&
call(void Button.click());
}</pre><p>
It does this by assuring that <code class="classname">Button</code> and
<code class="classname">ColorLabel</code> implement the appropriate
interfaces, declaring that they implement the methods required by
those interfaces, and providing a definition for the abstract
<code class="literal">stateChanges</code> pointcut. Now, every time a
<code class="classname">Button</code> is clicked, all
<code class="classname">ColorLabel</code> objects observing that button
will <code class="literal">colorCycle</code>.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1266"></a>Compiling and Running</h4></div></div></div><p>
<code class="classname">Demo</code> is the top class that starts this
demo. It instantiates a two buttons and three observers and links
them together as subjects and observers. So to run the demo, go to
the <code class="filename">examples</code> directory and type:
</p><pre class="programlisting">
ajc -argfile observer/files.lst
java observer.Demo
</pre></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="a-simple-telecom-simulation"></a>A Simple Telecom Simulation</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/telecom</code>.)
</p><p>
This example illustrates some ways that dependent concerns can be
encoded with aspects. It uses an example system comprising a simple
model of telephone connections to which timing and billing features
are added using aspects, where the billing feature depends upon the
timing feature.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1278"></a>The Application</h4></div></div></div><p>
The example application is a simple simulation of a telephony
system in which customers make, accept, merge and hang-up both
local and long distance calls. The application architecture is in
three layers.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The basic objects provide basic functionality to simulate
customers, calls and connections (regular calls have one
connection, conference calls have more than one).
</p></li><li class="listitem"><p>
The timing feature is concerned with timing the connections
and keeping the total connection time per customer. Aspects
are used to add a timer to each connection and to manage the
total time per customer.
</p></li><li class="listitem"><p>
The billing feature is concerned with charging customers for
the calls they make. Aspects are used to calculate a charge
per connection and, upon termination of a connection, to add
the charge to the appropriate customer's bill. The billing
aspect builds upon the timing aspect: it uses a pointcut
defined in Timing and it uses the timers that are associated
with connections.
</p></li></ul></div><p>
The simulation of system has three configurations: basic, timing
and billing. Programs for the three configurations are in classes
<code class="classname">BasicSimulation</code>,
<code class="classname">TimingSimulation</code> and
<code class="classname">BillingSimulation</code>. These share a common
superclass <code class="classname">AbstractSimulation</code>, which
defines the method run with the simulation itself and the method
wait used to simulate elapsed time.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1293"></a>The Basic Objects</h4></div></div></div><p>
The telecom simulation comprises the classes
<code class="classname">Customer</code>, <code class="classname">Call</code> and
the abstract class <code class="classname">Connection</code> with its two
concrete subclasses <code class="classname">Local</code> and
<code class="classname">LongDistance</code>. Customers have a name and a
numeric area code. They also have methods for managing
calls. Simple calls are made between one customer (the caller)
and another (the receiver), a <code class="classname">Connection</code>
object is used to connect them. Conference calls between more
than two customers will involve more than one connection. A
customer may be involved in many calls at one time.
<span class="inlinemediaobject"><img src="telecom.gif"></span>
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1305"></a>The <code class="classname">Customer</code> class</h4></div></div></div><p>
<code class="classname">Customer</code> has methods
<code class="literal">call</code>, <code class="literal">pickup</code>,
<code class="literal">hangup</code> and <code class="literal">merge</code> for
managing calls.
</p><pre class="programlisting">
public class Customer {
private String name;
private int areacode;
private Vector calls = new Vector();
protected void removeCall(Call c){
calls.removeElement(c);
}
protected void addCall(Call c){
calls.addElement(c);
}
public Customer(String name, int areacode) {
this.name = name;
this.areacode = areacode;
}
public String toString() {
return name + "(" + areacode + ")";
}
public int getAreacode(){
return areacode;
}
public boolean localTo(Customer other){
return areacode == other.areacode;
}
public Call call(Customer receiver) {
Call call = new Call(this, receiver);
addCall(call);
return call;
}
public void pickup(Call call) {
call.pickup();
addCall(call);
}
public void hangup(Call call) {
call.hangup(this);
removeCall(call);
}
public void merge(Call call1, Call call2){
call1.merge(call2);
removeCall(call2);
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1315"></a>The <code class="classname">Call</code> class</h4></div></div></div><p>
Calls are created with a caller and receiver who are customers. If
the caller and receiver have the same area code then the call can
be established with a <code class="classname">Local</code> connection (see
below), otherwise a <code class="classname">LongDistance</code> connection
is required. A call comprises a number of connections between
customers. Initially there is only the connection between the
caller and receiver but additional connections can be added if
calls are merged to form conference calls.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1321"></a>The <code class="classname">Connection</code> class</h4></div></div></div><p>
The class <code class="classname">Connection</code> models the physical
details of establishing a connection between customers. It does
this with a simple state machine (connections are initially
<code class="literal">PENDING</code>, then <code class="literal">COMPLETED</code> and
finally <code class="literal">DROPPED</code>). Messages are printed to the
console so that the state of connections can be
observed. Connection is an abstract class with two concrete
subclasses: <code class="classname">Local</code> and
<code class="classname">LongDistance</code>.
</p><pre class="programlisting">
abstract class Connection {
public static final int PENDING = 0;
public static final int COMPLETE = 1;
public static final int DROPPED = 2;
Customer caller, receiver;
private int state = PENDING;
Connection(Customer a, Customer b) {
this.caller = a;
this.receiver = b;
}
public int getState(){
return state;
}
public Customer getCaller() { return caller; }
public Customer getReceiver() { return receiver; }
void complete() {
state = COMPLETE;
System.out.println("connection completed");
}
void drop() {
state = DROPPED;
System.out.println("connection dropped");
}
public boolean connects(Customer c){
return (caller == c || receiver == c);
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1332"></a>The <code class="literal">Local</code> and <code class="literal">LongDistance</code> classes</h4></div></div></div><p>
The two kinds of connections supported by our simulation are
<code class="literal">Local</code> and <code class="literal">LongDistance</code>
connections.
</p><pre class="programlisting">
class Local extends Connection {
Local(Customer a, Customer b) {
super(a, b);
System.out.println("[new local connection from " +
a + " to " + b + "]");
}
}
</pre><pre class="programlisting">
class LongDistance extends Connection {
LongDistance(Customer a, Customer b) {
super(a, b);
System.out.println("[new long distance connection from " +
a + " to " + b + "]");
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1341"></a>Compiling and Running the Basic Simulation</h4></div></div></div><p>
The source files for the basic system are listed in the file
<code class="filename">basic.lst</code>. To build and run the basic system,
in a shell window, type these commands:
</p><pre class="programlisting">
ajc -argfile telecom/basic.lst
java telecom.BasicSimulation
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1346"></a>The Timing aspect</h4></div></div></div><p>
The <code class="classname">Timing</code> aspect keeps track of total
connection time for each <code class="classname">Customer</code> by
starting and stopping a timer associated with each connection. It
uses some helper classes:
</p><div class="sect4"><div class="titlepage"><div><div><h5 class="title"><a name="idm1351"></a>The <code class="classname">Timer</code> class</h5></div></div></div><p>
A <code class="classname">Timer</code> object simply records the current
time when it is started and stopped, and returns their difference
when asked for the elapsed time. The aspect
<code class="classname">TimerLog</code> (below) can be used to cause the
start and stop times to be printed to standard output.
</p><pre class="programlisting">
class Timer {
long startTime, stopTime;
public void start() {
startTime = System.currentTimeMillis();
stopTime = startTime;
}
public void stop() {
stopTime = System.currentTimeMillis();
}
public long getTime() {
return stopTime - startTime;
}
}
</pre></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1358"></a>The <code class="classname">TimerLog</code> aspect</h4></div></div></div><p>
The <code class="classname">TimerLog</code> aspect can be included in a
build to get the timer to announce when it is started and
stopped.
</p><pre class="programlisting">
public aspect TimerLog {
after(Timer t): target(t) && call(* Timer.start()) {
System.err.println("Timer started: " + t.startTime);
}
after(Timer t): target(t) && call(* Timer.stop()) {
System.err.println("Timer stopped: " + t.stopTime);
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1364"></a>The <code class="classname">Timing</code> aspect</h4></div></div></div><p>
The <code class="classname">Timing</code> aspect is declares an
inter-type field <code class="literal">totalConnectTime</code> for
<code class="classname">Customer</code> to store the accumulated connection
time per <code class="classname">Customer</code>. It also declares that
each <code class="classname">Connection</code> object has a timer.
</p><pre class="programlisting">
public long Customer.totalConnectTime = 0;
private Timer Connection.timer = new Timer();
</pre><p>
Two pieces of after advice ensure that the timer is started when
a connection is completed and and stopped when it is dropped. The
pointcut <code class="literal">endTiming</code> is defined so that it can
be used by the <code class="classname">Billing</code> aspect.
</p><pre class="programlisting">
public aspect Timing {
public long Customer.totalConnectTime = 0;
public long getTotalConnectTime(Customer cust) {
return cust.totalConnectTime;
}
private Timer Connection.timer = new Timer();
public Timer getTimer(Connection conn) { return conn.timer; }
after (Connection c): target(c) && call(void Connection.complete()) {
getTimer(c).start();
}
pointcut endTiming(Connection c): target(c) &&
call(void Connection.drop());
after(Connection c): endTiming(c) {
getTimer(c).stop();
c.getCaller().totalConnectTime += getTimer(c).getTime();
c.getReceiver().totalConnectTime += getTimer(c).getTime();
}
}</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1377"></a>The <code class="literal">Billing</code> aspect</h4></div></div></div><p>
The Billing system adds billing functionality to the telecom
application on top of timing.
</p><p>
The <code class="classname">Billing</code> aspect declares that each
<code class="classname">Connection</code> has a <code class="literal">payer</code>
inter-type field to indicate who initiated the call and therefore
who is responsible to pay for it. It also declares the inter-type
method <code class="literal">callRate</code> of
<code class="classname">Connection</code> so that local and long distance
calls can be charged differently. The call charge must be
calculated after the timer is stopped; the after advice on pointcut
<code class="literal">Timing.endTiming</code> does this, and
<code class="classname">Billing</code> is declared to be more precedent
than <code class="classname">Timing</code> to make sure that this advice
runs after <code class="classname">Timing</code>'s advice on the same join
point. Finally, it declares inter-type methods and fields for
<code class="classname">Customer</code> to handle the
<code class="literal">totalCharge</code>.
</p><pre class="programlisting">
public aspect Billing {
// precedence required to get advice on endtiming in the right order
declare precedence: Billing, Timing;
public static final long LOCAL_RATE = 3;
public static final long LONG_DISTANCE_RATE = 10;
public Customer Connection.payer;
public Customer getPayer(Connection conn) { return conn.payer; }
after(Customer cust) returning (Connection conn):
args(cust, ..) && call(Connection+.new(..)) {
conn.payer = cust;
}
public abstract long Connection.callRate();
public long LongDistance.callRate() { return LONG_DISTANCE_RATE; }
public long Local.callRate() { return LOCAL_RATE; }
after(Connection conn): Timing.endTiming(conn) {
long time = Timing.aspectOf().getTimer(conn).getTime();
long rate = conn.callRate();
long cost = rate * time;
getPayer(conn).addCharge(cost);
}
public long Customer.totalCharge = 0;
public long getTotalCharge(Customer cust) { return cust.totalCharge; }
public void Customer.addCharge(long charge){
totalCharge += charge;
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1394"></a>Accessing the inter-type state</h4></div></div></div><p>
Both the aspects <code class="classname">Timing</code> and
<code class="classname">Billing</code> contain the definition of operations
that the rest of the system may want to access. For example, when
running the simulation with one or both aspects, we want to find
out how much time each customer spent on the telephone and how big
their bill is. That information is also stored in the classes, but
they are accessed through static methods of the aspects, since the
state they refer to is private to the aspect.
</p><p>
Take a look at the file
<code class="filename">TimingSimulation.java</code>. The most important
method of this class is the method
<code class="filename">report(Customer)</code>, which is used in the method
run of the superclass
<code class="classname">AbstractSimulation</code>. This method is intended
to print out the status of the customer, with respect to the
<code class="classname">Timing</code> feature.
</p><pre class="programlisting">
protected void report(Customer c){
Timing t = Timing.aspectOf();
System.out.println(c + " spent " + t.getTotalConnectTime(c));
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1405"></a>Compiling and Running</h4></div></div></div><p>
The files timing.lst and billing.lst contain file lists for the
timing and billing configurations. To build and run the application
with only the timing feature, go to the directory examples and
type:
</p><pre class="programlisting">
ajc -argfile telecom/timing.lst
java telecom.TimingSimulation
</pre><p>
To build and run the application with the timing and billing
features, go to the directory examples and type:
</p><pre class="programlisting">
ajc -argfile telecom/billing.lst
java telecom.BillingSimulation
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1411"></a>Discussion</h4></div></div></div><p>
There are some explicit dependencies between the aspects Billing
and Timing:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Billing is declared more precedent than Timing so that Billing's
after advice runs after that of Timing when they are on the
same join point.
</p></li><li class="listitem"><p>
Billing uses the pointcut Timing.endTiming.
</p></li><li class="listitem"><p>
Billing needs access to the timer associated with a connection.
</p></li></ul></div><p>
</p></div></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-reusable"></a>Reusable Aspects</h2></div></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="tracing-using-aspects-revisited"></a>Tracing using Aspects, Revisited</h3></div></div></div><p>
(The code for this example is in
<code class="filename"><em class="replaceable"><code>InstallDir</code></em>/examples/tracing</code>.)
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm1428"></a>Tracing—Version 3</h4></div></div></div><p>
One advantage of not exposing the methods traceEntry and
traceExit as public operations is that we can easily change their
interface without any dramatic consequences in the rest of the
code.
</p><p>
Consider, again, the program without AspectJ. Suppose, for
example, that at some point later the requirements for tracing
change, stating that the trace messages should always include the
string representation of the object whose methods are being
traced. This can be achieved in at least two ways. One way is
keep the interface of the methods <code class="literal">traceEntry</code>
and <code class="literal">traceExit</code> as it was before,
</p><pre class="programlisting">
public static void traceEntry(String str);
public static void traceExit(String str);
</pre><p>
In this case, the caller is responsible for ensuring that the
string representation of the object is part of the string given
as argument. So, calls must look like:
</p><pre class="programlisting">
Trace.traceEntry("Square.distance in " + toString());
</pre><p>
Another way is to enforce the requirement with a second argument
in the trace operations, e.g.
</p><pre class="programlisting">
public static void traceEntry(String str, Object obj);
public static void traceExit(String str, Object obj);
</pre><p>
In this case, the caller is still responsible for sending the
right object, but at least there is some guarantees that some
object will be passed. The calls will look like:
</p><pre class="programlisting">
Trace.traceEntry("Square.distance", this);
</pre><p>
In either case, this change to the requirements of tracing will
have dramatic consequences in the rest of the code -- every call
to the trace operations traceEntry and traceExit must be changed!
</p><p>
Here's another advantage of doing tracing with an aspect. We've
already seen that in version 2 <code class="literal">traceEntry</code> and
<code class="literal">traceExit</code> are not publicly exposed. So
changing their interfaces, or the way they are used, has only a
small effect inside the <code class="classname">Trace</code>
class. Here's a partial view at the implementation of
<code class="classname">Trace</code>, version 3. The differences with
respect to version 2 are stressed in the comments:
</p><pre class="programlisting">
abstract aspect Trace {
public static int TRACELEVEL = 0;
protected static PrintStream stream = null;
protected static int callDepth = 0;
public static void initStream(PrintStream s) {
stream = s;
}
protected static void traceEntry(String str, Object o) {
if (TRACELEVEL == 0) return;
if (TRACELEVEL == 2) callDepth++;
printEntering(str + ": " + o.toString());
}
protected static void traceExit(String str, Object o) {
if (TRACELEVEL == 0) return;
printExiting(str + ": " + o.toString());
if (TRACELEVEL == 2) callDepth--;
}
private static void printEntering(String str) {
printIndent();
stream.println("Entering " + str);
}
private static void printExiting(String str) {
printIndent();
stream.println("Exiting " + str);
}
private static void printIndent() {
for (int i = 0; i < callDepth; i++)
stream.print(" ");
}
abstract pointcut myClass(Object obj);
pointcut myConstructor(Object obj): myClass(obj) && execution(new(..));
pointcut myMethod(Object obj): myClass(obj) &&
execution(* *(..)) && !execution(String toString());
before(Object obj): myConstructor(obj) {
traceEntry("" + thisJoinPointStaticPart.getSignature(), obj);
}
after(Object obj): myConstructor(obj) {
traceExit("" + thisJoinPointStaticPart.getSignature(), obj);
}
before(Object obj): myMethod(obj) {
traceEntry("" + thisJoinPointStaticPart.getSignature(), obj);
}
after(Object obj): myMethod(obj) {
traceExit("" + thisJoinPointStaticPart.getSignature(), obj);
}
}
</pre><p>
As you can see, we decided to apply the first design by preserving
the interface of the methods <code class="literal">traceEntry</code> and
<code class="literal">traceExit</code>. But it doesn't matter—we could
as easily have applied the second design (the code in the directory
<code class="filename">examples/tracing/version3</code> has the second
design). The point is that the effects of this change in the
tracing requirements are limited to the
<code class="classname">Trace</code> aspect class.
</p><p>
One implementation change worth noticing is the specification of
the pointcuts. They now expose the object. To maintain full
consistency with the behavior of version 2, we should have included
tracing for static methods, by defining another pointcut for static
methods and advising it. We leave that as an exercise.
</p><p>
Moreover, we had to exclude the execution join point of the method
<code class="filename">toString</code> from the <code class="literal">methods</code>
pointcut. The problem here is that <code class="literal">toString</code> is
being called from inside the advice. Therefore if we trace it, we
will end up in an infinite recursion of calls. This is a subtle
point, and one that you must be aware when writing advice. If the
advice calls back to the objects, there is always the possibility
of recursion. Keep that in mind!
</p><p>
In fact, esimply excluding the execution join point may not be
enough, if there are calls to other traced methods within it -- in
which case, the restriction should be
</p><pre class="programlisting">
&& !cflow(execution(String toString()))
</pre><p>
excluding both the execution of toString methods and all join
points under that execution.
</p><p>
In summary, to implement the change in the tracing requirements we
had to make a couple of changes in the implementation of the
<code class="classname">Trace</code> aspect class, including changing the
specification of the pointcuts. That's only natural. But the
implementation changes were limited to this aspect. Without
aspects, we would have to change the implementation of every
application class.
</p><p>
Finally, to run this version of tracing, go to the directory
<code class="filename">examples</code> and type:
</p><pre class="programlisting">
ajc -argfile tracing/tracev3.lst
</pre><p>
The file tracev3.lst lists the application classes as well as this
version of the files <code class="filename">Trace.java</code> and
<code class="filename">TraceMyClasses.java</code>. To run the program, type
</p><pre class="programlisting">
java tracing.version3.TraceMyClasses
</pre><p>The output should be:</p><pre class="programlisting">
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Circle(double, double, double)
<-- tracing.Circle(double, double, double)
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Circle(double, double, double)
<-- tracing.Circle(double, double, double)
--> tracing.Circle(double)
<-- tracing.Circle(double)
--> tracing.TwoDShape(double, double)
<-- tracing.TwoDShape(double, double)
--> tracing.Square(double, double, double)
<-- tracing.Square(double, double, double)
--> tracing.Square(double, double)
<-- tracing.Square(double, double)
--> double tracing.Circle.perimeter()
<-- double tracing.Circle.perimeter()
c1.perimeter() = 12.566370614359172
--> double tracing.Circle.area()
<-- double tracing.Circle.area()
c1.area() = 12.566370614359172
--> double tracing.Square.perimeter()
<-- double tracing.Square.perimeter()
s1.perimeter() = 4.0
--> double tracing.Square.area()
<-- double tracing.Square.area()
s1.area() = 1.0
--> double tracing.TwoDShape.distance(TwoDShape)
--> double tracing.TwoDShape.getX()
<-- double tracing.TwoDShape.getX()
--> double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.distance(TwoDShape)
c2.distance(c1) = 4.242640687119285
--> double tracing.TwoDShape.distance(TwoDShape)
--> double tracing.TwoDShape.getX()
<-- double tracing.TwoDShape.getX()
--> double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.getY()
<-- double tracing.TwoDShape.distance(TwoDShape)
s1.distance(c1) = 2.23606797749979
--> String tracing.Square.toString()
--> String tracing.TwoDShape.toString()
<-- String tracing.TwoDShape.toString()
<-- String tracing.Square.toString()
s1.toString(): Square side = 1.0 @ (1.0, 2.0)
</pre></div></div></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="idioms"></a>Chapter 4. Idioms</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#idioms-intro">Introduction</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idioms-intro"></a>Introduction</h2></div></div></div><p>
This chapter consists of very short snippets of AspectJ code,
typically pointcuts, that are particularly evocative or useful.
This section is a work in progress.
</p><p>
Here's an example of how to enfore a rule that code in the
java.sql package can only be used from one particular package in
your system. This doesn't require any access to code in the
java.sql package.
</p><pre class="programlisting">
/* Any call to methods or constructors in java.sql */
pointcut restrictedCall():
call(* java.sql.*.*(..)) || call(java.sql.*.new(..));
/* Any code in my system not in the sqlAccess package */
pointcut illegalSource():
within(com.foo..*) && !within(com.foo.sqlAccess.*);
declare error: restrictedCall() && illegalSource():
"java.sql package can only be accessed from com.foo.sqlAccess";
</pre><p>Any call to an instance of a subtype of AbstractFacade whose class is
not exactly equal to AbstractFacade:</p><pre class="programlisting">
pointcut nonAbstract(AbstractFacade af):
call(* *(..))
&& target(af)
&& !if(af.getClass() == AbstractFacade.class);
</pre><p> If AbstractFacade is an abstract class or an interface, then every
instance must be of a subtype and you can replace this with: </p><pre class="programlisting">
pointcut nonAbstract(AbstractFacade af):
call(* *(..))
&& target(af);
</pre><p> Any call to a method which is defined by a subtype of
AbstractFacade, but which isn't defined by the type AbstractFacade itself:
</p><pre class="programlisting">
pointcut callToUndefinedMethod():
call(* AbstractFacade+.*(..))
&& !call(* AbstractFacade.*(..));
</pre><p> The execution of a method that is defined in the source code for a
type that is a subtype of AbstractFacade but not in AbstractFacade itself:
</p><pre class="programlisting">
pointcut executionOfUndefinedMethod():
execution(* *(..))
&& within(AbstractFacade+)
&& !within(AbstractFacade)
</pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="pitfalls"></a>Chapter 5. Pitfalls</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#pitfalls-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#pitfalls-infiniteLoops">Infinite loops</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="pitfalls-intro"></a>Introduction</h2></div></div></div><p>
This chapter consists of a few AspectJ programs that may lead to
surprising behavior and how to understand them.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="pitfalls-infiniteLoops"></a>Infinite loops</h2></div></div></div><p>
Here is a Java program with peculiar behavior
</p><pre class="programlisting">
public class Main {
public static void main(String[] args) {
foo();
System.out.println("done with call to foo");
}
static void foo() {
try {
foo();
} finally {
foo();
}
}
}
</pre><p>
This program will never reach the println call, but when it aborts
may have no stack trace.
</p><p>
This silence is caused by multiple StackOverflowExceptions. First
the infinite loop in the body of the method generates one, which the
finally clause tries to handle. But this finally clause also
generates an infinite loop which the current JVMs can't handle
gracefully leading to the completely silent abort.
</p><p>
The following short aspect will also generate this behavior:
</p><pre class="programlisting">
aspect A {
before(): call(* *(..)) { System.out.println("before"); }
after(): call(* *(..)) { System.out.println("after"); }
}
</pre><p>
Why? Because the call to println is also a call matched by the
pointcut <code class="literal">call (* *(..))</code>. We get no output because
we used simple after() advice. If the aspect were changed to
</p><pre class="programlisting">
aspect A {
before(): call(* *(..)) { System.out.println("before"); }
after() returning: call(* *(..)) { System.out.println("after"); }
}
</pre><p>
Then at least a StackOverflowException with a stack trace would be
seen. In both cases, though, the overall problem is advice applying
within its own body.
</p><p>
There's a simple idiom to use if you ever have a worry that your
advice might apply in this way. Just restrict the advice from occurring in
join points caused within the aspect. So:
</p><pre class="programlisting">
aspect A {
before(): call(* *(..)) && !within(A) { System.out.println("before"); }
after() returning: call(* *(..)) && !within(A) { System.out.println("after"); }
}
</pre><p>
Other solutions might be to more closely restrict the pointcut in
other ways, for example:
</p><pre class="programlisting">
aspect A {
before(): call(* MyObject.*(..)) { System.out.println("before"); }
after() returning: call(* MyObject.*(..)) { System.out.println("after"); }
}
</pre><p>
The moral of the story is that unrestricted generic pointcuts can
pick out more join points than intended.
</p></div></div><div class="appendix"><div class="titlepage"><div><div><h1 class="title"><a name="quick"></a>Appendix A. AspectJ Quick Reference</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#quick-pointcuts">Pointcuts</a></span></dt><dt><span class="sect1"><a href="#quick-typePatterns">Type Patterns</a></span></dt><dt><span class="sect1"><a href="#quick-advice">Advice</a></span></dt><dt><span class="sect1"><a href="#quick-interType">Inter-type member declarations</a></span></dt><dt><span class="sect1"><a href="#quick-other">Other declarations</a></span></dt><dt><span class="sect1"><a href="#quick-aspectAssociations">Aspects</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-pointcuts"></a>Pointcuts</h2></div></div></div><div class="informaltable"><table class="informaltable" border="0"><colgroup><col align="left" class="c1"><col align="left" class="c2"></colgroup><tbody valign="top"><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Methods and Constructors</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">call(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every call to any method or constructor matching
<em class="replaceable"><code>Signature</code></em> at the call site
</td></tr><tr><td align="left" valign="top">
<code class="literal">execution(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every execution of any method or constructor matching
<em class="replaceable"><code>Signature</code></em>
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Fields</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">get(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every reference to any field matching <em class="replaceable"><code>Signature</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal">set(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every assignment to any field matching
<em class="replaceable"><code>Signature</code></em>. The assigned value can
be exposed with an <code class="literal">args</code> pointcut
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Exception Handlers</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">handler(<em class="replaceable"><code>TypePattern</code></em>)</code>
</td><td align="left" valign="top">
every exception handler for any <code class="literal">Throwable</code>
type in <em class="replaceable"><code>TypePattern</code></em>. The exception
value can be exposed with an <code class="literal">args</code> pointcut
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Advice</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">adviceexecution()</code>
</td><td align="left" valign="top">
every execution of any piece of advice
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Initialization</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">staticinitialization(<em class="replaceable"><code>TypePattern</code></em>)</code>
</td><td align="left" valign="top">
every execution of a static initializer for any type in
<em class="replaceable"><code>TypePattern</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal">initialization(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every initialization of an object when the first constructor
called in the type matches
<em class="replaceable"><code>Signature</code></em>, encompassing the return
from the super constructor call to the return of the
first-called constructor
</td></tr><tr><td align="left" valign="top">
<code class="literal">preinitialization(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every pre-initialization of an object when the first
constructor called in the type matches
<em class="replaceable"><code>Signature</code></em>, encompassing the entry
of the first-called constructor to the call to the super
constructor
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Lexical</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">within(<em class="replaceable"><code>TypePattern</code></em>)</code>
</td><td align="left" valign="top">
every join point from code defined in a type in
<em class="replaceable"><code>TypePattern</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal">withincode(<em class="replaceable"><code>Signature</code></em>)</code>
</td><td align="left" valign="top">
every join point from code defined in a method or constructor
matching <em class="replaceable"><code>Signature</code></em>
</td></tr></tbody></table><table class="informaltable" border="0"><colgroup><col align="left" class="c1"><col align="left" class="c2"></colgroup><tbody valign="top"><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Instanceof checks and context exposure</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">this(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code>
</td><td align="left" valign="top">
every join point when the currently executing object is an
instance of <em class="replaceable"><code>Type</code></em> or
<em class="replaceable"><code>Id</code></em>'s type
</td></tr><tr><td align="left" valign="top">
<code class="literal">target(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code>
</td><td align="left" valign="top">
every join point when the target executing object is an
instance of <em class="replaceable"><code>Type</code></em> or
<em class="replaceable"><code>Id</code></em>'s type
</td></tr><tr><td align="left" valign="top">
<code class="literal">args(<em class="replaceable"><code>Type</code></em> or
<em class="replaceable"><code>Id</code></em>, ...)</code>
</td><td align="left" valign="top">
every join point when the arguments are instances of
<em class="replaceable"><code>Type</code></em>s or the types of the
<em class="replaceable"><code>Id</code></em>s
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Control Flow</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">cflow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
every join point in the control flow of each join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>, including
<em class="replaceable"><code>P</code></em> itself
</td></tr><tr><td align="left" valign="top">
<code class="literal">cflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
every join point below the control flow of each join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>; does not include
<em class="replaceable"><code>P</code></em> itself
</td></tr><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Conditional</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">if(<em class="replaceable"><code>Expression</code></em>)</code>
</td><td align="left" valign="top">
every join point when the boolean
<em class="replaceable"><code>Expression</code></em> is
<code class="literal">true</code>
</td></tr></tbody></table><table class="informaltable" border="0"><colgroup><col align="left" class="c1"><col align="left" class="c2"></colgroup><tbody valign="top"><tr><td colspan="2" align="left" valign="top">
<span class="bold"><strong>Combination</strong></span>
</td></tr><tr><td align="left" valign="top">
<code class="literal">! <em class="replaceable"><code>Pointcut</code></em></code>
</td><td align="left" valign="top">
every join point not picked out by
<em class="replaceable"><code>Pointcut</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal"><em class="replaceable"><code>Pointcut0</code></em> && <em class="replaceable"><code>Pointcut1</code></em></code>
</td><td align="left" valign="top">
each join point picked out by both
<em class="replaceable"><code>Pointcut0</code></em> and
<em class="replaceable"><code>Pointcut1</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal"><em class="replaceable"><code>Pointcut0</code></em> || <em class="replaceable"><code>Pointcut1</code></em></code>
</td><td align="left" valign="top">
each join point picked out by either
<em class="replaceable"><code>Pointcut0</code></em> or
<em class="replaceable"><code>Pointcut1</code></em>
</td></tr><tr><td align="left" valign="top">
<code class="literal">( <em class="replaceable"><code>Pointcut</code></em> )</code>
</td><td align="left" valign="top">
each join point picked out by
<em class="replaceable"><code>Pointcut</code></em>
</td></tr></tbody></table></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-typePatterns"></a>Type Patterns</h2></div></div></div><p>
A type pattern is one of
</p><div class="informaltable"><table class="informaltable" border="0"><colgroup><col><col></colgroup><tbody valign="top"><tr><td valign="top"><em class="replaceable"><code>TypeNamePattern</code></em></td><td valign="top">all types in <em class="replaceable"><code>TypeNamePattern</code></em></td></tr><tr><td valign="top"><em class="replaceable"><code>SubtypePattern</code></em></td><td valign="top">all types in <em class="replaceable"><code>SubtypePattern</code></em>, a
pattern with a +. </td></tr><tr><td valign="top"><em class="replaceable"><code>ArrayTypePattern</code></em></td><td valign="top">all types in <em class="replaceable"><code>ArrayTypePattern</code></em>,
a pattern with one or more []s. </td></tr><tr><td valign="top"><code class="literal">!<em class="replaceable"><code>TypePattern</code></em></code></td><td valign="top">all types not in <em class="replaceable"><code>TypePattern</code></em></td></tr><tr><td valign="top"><code class="literal"><em class="replaceable"><code>TypePattern0</code></em>
&& <em class="replaceable"><code>TypePattern1</code></em></code></td><td valign="top">all types in both
<em class="replaceable"><code>TypePattern0</code></em> and <em class="replaceable"><code>TypePattern1</code></em></td></tr><tr><td valign="top"><code class="literal"><em class="replaceable"><code>TypePattern0</code></em> || <em class="replaceable"><code>TypePattern1</code></em></code></td><td valign="top">all types in either
<em class="replaceable"><code>TypePattern0</code></em> or <em class="replaceable"><code>TypePattern1</code></em></td></tr><tr><td valign="top"><code class="literal">( <em class="replaceable"><code>TypePattern</code></em> )</code></td><td valign="top">all types in <em class="replaceable"><code>TypePattern</code></em></td></tr></tbody></table></div><p>
where <em class="replaceable"><code>TypeNamePattern</code></em> can either be a
plain type name, the wildcard <code class="literal">*</code> (indicating all
types), or an identifier with embedded <code class="literal">*</code> and
<code class="literal">..</code> wildcards.
</p><p>
An embedded <code class="literal">*</code> in an identifier matches any
sequence of characters, but does not match the package (or
inner-type) separator ".".
</p><p>
An embedded <code class="literal">..</code> in an identifier matches any
sequence of characters that starts and ends with the package (or
inner-type) separator ".".
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-advice"></a>Advice</h2></div></div></div><p>
Each piece of advice is of the form
</p><div class="blockquote"><blockquote class="blockquote"><code class="literal">[ strictfp ] <em class="replaceable"><code>AdviceSpec</code></em>
[ throws <em class="replaceable"><code>TypeList</code></em> ] :
<em class="replaceable"><code>Pointcut</code></em> {
<em class="replaceable"><code>Body</code></em> } </code></blockquote></div><p>
where <em class="replaceable"><code>AdviceSpec</code></em> is one of
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
<code class="literal">before( <em class="replaceable"><code>Formals</code></em> ) </code>
</span></dt><dd>
runs before each join point
</dd><dt><span class="term">
<code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) returning
[ ( <em class="replaceable"><code>Formal</code></em> ) ] </code>
</span></dt><dd>
runs after each join point that returns normally. The
optional formal gives access to the returned value
</dd><dt><span class="term">
<code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) throwing [
( <em class="replaceable"><code>Formal</code></em> ) ] </code>
</span></dt><dd>
runs after each join point that throws a
<code class="literal">Throwable</code>. If the optional formal is
present, runs only after each join point that throws a
<code class="literal">Throwable</code> of the type of
<em class="replaceable"><code>Formal</code></em>, and
<em class="replaceable"><code>Formal</code></em> gives access to the
<code class="literal">Throwable</code> exception value
</dd><dt><span class="term">
<code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) </code>
</span></dt><dd>
runs after each join point regardless of whether it returns
normally or throws a <code class="literal">Throwable</code></dd><dt><span class="term">
<code class="literal"><em class="replaceable"><code>Type</code></em>
around( <em class="replaceable"><code>Formals</code></em> ) </code>
</span></dt><dd>
runs in place of each join point. The join point can be
executed by calling <code class="literal">proceed</code>, which takes
the same number and types of arguments as the around advice.
</dd></dl></div><p>
Three special variables are available inside of advice bodies:
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
<code class="literal">thisJoinPoint</code>
</span></dt><dd>
an object of type <a class="ulink" href="../api/org/aspectj/lang/JoinPoint.html" target="_top"><code class="literal">org.aspectj.lang.JoinPoint</code></a>
representing the join point at which the advice is executing.
</dd><dt><span class="term">
<code class="literal">thisJoinPointStaticPart</code>
</span></dt><dd>
equivalent to <code class="literal">thisJoinPoint.getStaticPart()</code>,
but may use fewer runtime resources.
</dd><dt><span class="term">
<code class="literal">thisEnclosingJoinPointStaticPart</code>
</span></dt><dd>
the static part of the dynamically enclosing join point.
</dd></dl></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-interType"></a>Inter-type member declarations</h2></div></div></div><p>
Each inter-type member is one of
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
<code class="literal">
<em class="replaceable"><code>Modifiers ReturnType OnType . Id</code></em>
( <em class="replaceable"><code>Formals</code></em> )
[ throws <em class="replaceable"><code>TypeList</code></em> ]
{ <em class="replaceable"><code>Body</code></em> }
</code>
</span></dt><dd>
a method on <em class="replaceable"><code>OnType</code></em>.
</dd><dt><span class="term">
<code class="literal">
abstract <em class="replaceable"><code>Modifiers ReturnType OnType . Id</code></em>
( <em class="replaceable"><code>Formals</code></em> )
[ throws <em class="replaceable"><code>TypeList</code></em> ] ;
</code>
</span></dt><dd>
an abstract method on <em class="replaceable"><code>OnType</code></em>.
</dd><dt><span class="term">
<code class="literal">
<em class="replaceable"><code>Modifiers OnType . </code></em> new
( <em class="replaceable"><code>Formals</code></em> )
[ throws <em class="replaceable"><code>TypeList</code></em> ]
{ <em class="replaceable"><code>Body</code></em> }
</code>
</span></dt><dd>
a constructor on <em class="replaceable"><code>OnType</code></em>.
</dd><dt><span class="term">
<code class="literal">
<em class="replaceable"><code>Modifiers Type OnType . Id </code></em>
[ = <em class="replaceable"><code>Expression</code></em> ] ;
</code>
</span></dt><dd>
a field on <em class="replaceable"><code>OnType</code></em>.
</dd></dl></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-other"></a>Other declarations</h2></div></div></div><div class="variablelist"><dl class="variablelist"><dt><span class="term">
<code class="literal">
declare parents :
<em class="replaceable"><code>TypePattern</code></em> extends
<em class="replaceable"><code>Type</code></em> ;
</code>
</span></dt><dd>
the types in <em class="replaceable"><code>TypePattern</code></em> extend
<em class="replaceable"><code>Type</code></em>.
</dd><dt><span class="term">
<code class="literal">
declare parents : <em class="replaceable"><code>TypePattern</code></em>
implements <em class="replaceable"><code>TypeList</code></em> ;
</code>
</span></dt><dd>
the types in <em class="replaceable"><code>TypePattern</code></em>
implement the types in <em class="replaceable"><code>TypeList</code></em>.
</dd><dt><span class="term">
<code class="literal">
declare warning : <em class="replaceable"><code>Pointcut</code></em> :
<em class="replaceable"><code>String</code></em> ;
</code>
</span></dt><dd>
if any of the join points in <em class="replaceable"><code>Pointcut</code></em>
possibly exist in the program, the compiler emits the warning
<em class="replaceable"><code>String</code></em>.
</dd><dt><span class="term">
<code class="literal">
declare error : <em class="replaceable"><code>Pointcut</code></em> :
<em class="replaceable"><code>String</code></em> ;
</code>
</span></dt><dd>
if any of the join points in <em class="replaceable"><code>Pointcut</code></em>
could possibly exist in the program, the compiler emits the
error <em class="replaceable"><code>String</code></em>.
</dd><dt><span class="term">
<code class="literal">
declare soft :
<em class="replaceable"><code>Type</code></em> :
<em class="replaceable"><code>Pointcut</code></em> ;
</code>
</span></dt><dd>
any <em class="replaceable"><code>Type</code></em> exception
that gets thrown at any join point picked out by
<em class="replaceable"><code>Pointcut</code></em> is wrapped in <a class="ulink" href="../api/org/aspectj/lang/SoftException.html" target="_top"><code class="literal">org.aspectj.lang.SoftException</code></a>.
</dd><dt><span class="term">
<code class="literal">
declare precedence :
<em class="replaceable"><code>TypePatternList</code></em> ;
</code>
</span></dt><dd>
at any join point where multiple pieces of advice
apply, the advice precedence at that join point is in
<em class="replaceable"><code>TypePatternList</code></em> order.
</dd></dl></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-aspectAssociations"></a>Aspects</h2></div></div></div><p>
Each aspect is of the form
</p><div class="blockquote"><blockquote class="blockquote"><code class="literal">
[ privileged ] <em class="replaceable"><code>Modifiers</code></em>
aspect <em class="replaceable"><code>Id</code></em>
[ extends <em class="replaceable"><code>Type</code></em> ]
[ implements <em class="replaceable"><code>TypeList</code></em> ]
[ <em class="replaceable"><code>PerClause</code></em> ]
{ <em class="replaceable"><code>Body</code></em> }
</code></blockquote></div><p>
where <em class="replaceable"><code>PerClause</code></em> defines how the aspect is
instantiated and associated (<code class="literal">issingleton()</code> by
default):
</p><div class="informaltable"><table class="informaltable" border="0"><colgroup><col><col><col></colgroup><thead><tr><th align="left">PerClause</th><th align="left">Description</th><th align="left">Accessor</th></tr></thead><tbody valign="top"><tr><td align="left" valign="top">
[ <code class="literal">issingleton()</code> ]
</td><td align="left" valign="top">
One instance of the aspect is made. This is
the default.
</td><td align="left" valign="top">
<code class="literal">aspectOf()</code> at all join points
</td></tr><tr><td align="left" valign="top">
<code class="literal">perthis(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
An instance is associated with each object that is the
currently executing object at any join point in
<em class="replaceable"><code>Pointcut</code></em>.
</td><td align="left" valign="top">
<code class="literal">aspectOf(Object)</code> at all join points
</td></tr><tr><td align="left" valign="top">
<code class="literal">pertarget(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
An instance is associated with each object that is the
target object at any join point in
<em class="replaceable"><code>Pointcut</code></em>.
</td><td align="left" valign="top">
<code class="literal">aspectOf(Object)</code> at all join points
</td></tr><tr><td align="left" valign="top">
<code class="literal">percflow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
The aspect is defined for each entrance to the control flow of
the join points defined by <em class="replaceable"><code>Pointcut</code></em>. </td><td align="left" valign="top">
<code class="literal">aspectOf()</code> at join points in
<code class="literal">cflow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td></tr><tr><td align="left" valign="top">
<code class="literal">percflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td><td align="left" valign="top">
The aspect is defined for each entrance to the control flow
below the join points defined by <em class="replaceable"><code>Pointcut</code></em>.
</td><td align="left" valign="top">
<code class="literal">aspectOf()</code> at join points in
<code class="literal">cflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code>
</td></tr></tbody></table></div></div></div><div class="appendix"><div class="titlepage"><div><div><h1 class="title"><a name="semantics"></a>Appendix B. Language Semantics</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#semantics-intro">Introduction</a></span></dt><dt><span class="sect1"><a href="#semantics-joinPoints">Join Points</a></span></dt><dt><span class="sect1"><a href="#semantics-pointcuts">Pointcuts</a></span></dt><dd><dl><dt><span class="sect2"><a href="#pointcut-definition">Pointcut definition</a></span></dt><dt><span class="sect2"><a href="#context-exposure">Context exposure</a></span></dt><dt><span class="sect2"><a href="#primitive-pointcuts">Primitive pointcuts</a></span></dt><dt><span class="sect2"><a href="#signatures">Signatures</a></span></dt><dt><span class="sect2"><a href="#matching">Matching</a></span></dt><dt><span class="sect2"><a href="#type-patterns">Type patterns</a></span></dt><dt><span class="sect2"><a href="#pattern-summary">Pattern Summary</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-advice">Advice</a></span></dt><dd><dl><dt><span class="sect2"><a href="#advice-modifiers">Advice modifiers</a></span></dt><dt><span class="sect2"><a href="#advice-and-checked-exceptions">Advice and checked exceptions</a></span></dt><dt><span class="sect2"><a href="#advice-precedence">Advice precedence</a></span></dt><dt><span class="sect2"><a href="#reflective-access-to-the-join-point">Reflective access to the join point</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-declare">Static crosscutting</a></span></dt><dd><dl><dt><span class="sect2"><a href="#inter-type-member-declarations">Inter-type member declarations</a></span></dt><dt><span class="sect2"><a href="#access-modifiers">Access modifiers</a></span></dt><dt><span class="sect2"><a href="#conflicts">Conflicts</a></span></dt><dt><span class="sect2"><a href="#extension-and-implementation">Extension and Implementation</a></span></dt><dt><span class="sect2"><a href="#interfaces-with-members">Interfaces with members</a></span></dt><dt><span class="sect2"><a href="#warnings-and-errors">Warnings and Errors</a></span></dt><dt><span class="sect2"><a href="#softened-exceptions">Softened exceptions</a></span></dt><dt><span class="sect2"><a href="#advice-precedence">Advice Precedence</a></span></dt><dt><span class="sect2"><a href="#statically-determinable-pointcuts">Statically determinable pointcuts</a></span></dt></dl></dd><dt><span class="sect1"><a href="#semantics-aspects">Aspects</a></span></dt><dd><dl><dt><span class="sect2"><a href="#aspect-declaration">Aspect Declaration</a></span></dt><dt><span class="sect2"><a href="#aspect-extension">Aspect Extension</a></span></dt><dt><span class="sect2"><a href="#aspect-instantiation">Aspect instantiation</a></span></dt><dt><span class="sect2"><a href="#aspect-privilege">Aspect privilege</a></span></dt></dl></dd></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-intro"></a>Introduction</h2></div></div></div><p>
AspectJ extends Java by overlaying a concept of join points onto the
existing Java semantics and adding a few new program elements to Java:
</p><p>
A join point is a well-defined point in the execution of a
program. These include method and constructor calls, field accesses and
others described below.
</p><p>
A pointcut picks out join points, and exposes some of the values in the
execution context of those join points. There are several primitive
pointcut designators, and others can be named and defined by the
<code class="literal">pointcut</code> declaration.
</p><p>
A piece of advice is code that executes at each join point in a
pointcut. Advice has access to the values exposed by the
pointcut. Advice is defined by <code class="literal">before</code>,
<code class="literal">after</code>, and <code class="literal">around</code> declarations.
</p><p>
Inter-type declarations form AspectJ's static crosscutting features,
that is, is code that may change the type structure of a program, by
adding to or extending interfaces and classes with new fields,
constructors, or methods. Some inter-type declarations are defined
through an extension of usual method, field, and constructor
declarations, and other declarations are made with a new
<code class="literal">declare</code> keyword.
</p><p>
An aspect is a crosscutting type that encapsulates pointcuts, advice,
and static crosscutting features. By type, we mean Java's notion: a
modular unit of code, with a well-defined interface, about which it is
possible to do reasoning at compile time. Aspects are defined by the
<code class="literal">aspect</code> declaration.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-joinPoints"></a>Join Points</h2></div></div></div><p>
While aspects define types that crosscut, the AspectJ system does not
allow completely arbitrary crosscutting. Rather, aspects define types
that cut across principled points in a program's execution. These
principled points are called join points.
</p><p>
A join point is a well-defined point in the execution of a
program. The join points defined by AspectJ are:
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">Method call</span></dt><dd>
When a method is called, not including super calls of
non-static methods.
</dd><dt><span class="term">Method execution</span></dt><dd>
When the body of code for an actual method executes.
</dd><dt><span class="term">Constructor call</span></dt><dd>
When an object is built and that object's initial constructor is
called (i.e., not for "super" or "this" constructor calls). The
object being constructed is returned at a constructor call join
point, so its return type is considered to be the type of the
object, and the object itself may be accessed with <code class="literal">after
returning</code> advice.
</dd><dt><span class="term">Constructor execution</span></dt><dd>
When the body of code for an actual constructor executes, after
its this or super constructor call. The object being constructed
is the currently executing object, and so may be accessed with
the <code class="literal">this</code> pointcut. The constructor execution
join point for a constructor that calls a super constructor also
includes any non-static initializers of enclosing class. No
value is returned from a constructor execution join point, so its
return type is considered to be void.
</dd><dt><span class="term">Static initializer execution</span></dt><dd>
When the static initializer for a class executes. No value is
returned from a static initializer execution join point, so its
return type is considered to be void.
</dd><dt><span class="term">Object pre-initialization</span></dt><dd>
Before the object initialization code for a particular class runs.
This encompasses the time between the start of its first called
constructor and the start of its parent's constructor. Thus, the
execution of these join points encompass the join points of the
evaluation of the arguments of <code class="literal">this()</code> and
<code class="literal">super()</code> constructor calls. No value is
returned from an object pre-initialization join point, so its
return type is considered to be void.
</dd><dt><span class="term">Object initialization</span></dt><dd>
When the object initialization code for a particular class runs.
This encompasses the time between the return of its parent's
constructor and the return of its first called constructor. It
includes all the dynamic initializers and constructors used to
create the object. The object being constructed is the currently
executing object, and so may be accessed with the
<code class="literal">this</code> pointcut. No value is returned from a
constructor execution join point, so its return type is
considered to be void.
</dd><dt><span class="term">Field reference</span></dt><dd>
When a non-constant field is referenced. [Note that references
to constant fields (static final fields bound to a constant
string object or primitive value) are not join points, since Java
requires them to be inlined.]
</dd><dt><span class="term">Field set</span></dt><dd>
When a field is assigned to.
Field set join points are considered to have one argument,
the value the field is being set to.
No value is returned from a field set join point, so
its return type is considered to be void.
[Note that the initializations of constant fields (static
final fields where the initializer is a constant string object or
primitive value) are not join points, since Java requires their
references to be inlined.]
</dd><dt><span class="term">Handler execution</span></dt><dd>
When an exception handler executes.
Handler execution join points are considered to have one argument,
the exception being handled.
No value is returned from a field set join point, so
its return type is considered to be void.
</dd><dt><span class="term">Advice execution</span></dt><dd>
When the body of code for a piece of advice executes.
</dd></dl></div><p>
Each join point potentially has three pieces of state associated
with it: the currently executing object, the target object, and
an object array of arguments. These are exposed by the three
state-exposing pointcuts, <code class="literal">this</code>,
<code class="literal">target</code>, and <code class="literal">args</code>,
respectively.
</p><p>
Informally, the currently executing object is the object that a
<code class="literal">this</code> expression would pick out at the join
point. The target object is where control or attention is
transferred to by the join point. The arguments are those
values passed for that transfer of control or attention.
</p><div class="informaltable"><table class="informaltable" border="1"><colgroup><col><col><col><col></colgroup><thead valign="top"><tr><th align="left" valign="top"><span class="bold"><strong>Join Point</strong></span></th><th align="left" valign="top"><span class="bold"><strong>Current Object</strong></span></th><th align="left" valign="top"><span class="bold"><strong>Target Object</strong></span></th><th align="left" valign="top"><span class="bold"><strong>Arguments</strong></span></th></tr></thead><tbody><tr><td align="left">Method Call</td><td align="left">executing object*</td><td align="left">target object**</td><td align="left">method arguments</td></tr><tr><td align="left">Method Execution</td><td align="left">executing object*</td><td align="left">executing object*</td><td align="left">method arguments</td></tr><tr><td align="left">Constructor Call</td><td align="left">executing object*</td><td align="left">None</td><td align="left">constructor arguments</td></tr><tr><td align="left">Constructor Execution</td><td align="left">executing object</td><td align="left">executing object</td><td align="left">constructor arguments</td></tr><tr><td align="left">Static initializer execution</td><td align="left">None</td><td align="left">None</td><td align="left">None</td></tr><tr><td align="left">Object pre-initialization</td><td align="left">None</td><td align="left">None</td><td align="left">constructor arguments</td></tr><tr><td align="left">Object initialization</td><td align="left">executing object</td><td align="left">executing object</td><td align="left">constructor arguments</td></tr><tr><td align="left">Field reference</td><td align="left">executing object*</td><td align="left">target object**</td><td align="left">None</td></tr><tr><td align="left">Field assignment</td><td align="left">executing object*</td><td align="left">target object**</td><td align="left">assigned value</td></tr><tr><td align="left">Handler execution</td><td align="left">executing object*</td><td align="left">executing object*</td><td align="left">caught exception</td></tr><tr><td align="left">Advice execution</td><td align="left">executing aspect</td><td align="left">executing aspect</td><td align="left">advice arguments</td></tr></tbody></table></div><p>* There is no executing object in static contexts such as
static method bodies or static initializers.
</p><p>** There is no target object for join points associated
with static methods or fields.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-pointcuts"></a>Pointcuts</h2></div></div></div><p>
A pointcut is a program element that picks out join points and
exposes data from the execution context of those join points.
Pointcuts are used primarily by advice. They can be composed with
boolean operators to build up other pointcuts. The primitive
pointcuts and combinators provided by the language are:
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="literal">call(<em class="replaceable"><code>MethodPattern</code></em>)</code></span></dt><dd>
Picks out each method call join point whose signature matches
<em class="replaceable"><code>MethodPattern</code></em>.
</dd><dt><span class="term"><code class="literal">execution(<em class="replaceable"><code>MethodPattern</code></em>)</code></span></dt><dd>
Picks out each method execution join point whose signature matches
<em class="replaceable"><code>MethodPattern</code></em>.
</dd><dt><span class="term"><code class="literal">get(<em class="replaceable"><code>FieldPattern</code></em>)</code></span></dt><dd>
Picks out each field reference join point whose signature matches
<em class="replaceable"><code>FieldPattern</code></em>.
[Note that references to constant fields (static final
fields bound to a constant string object or primitive value) are not
join points, since Java requires them to be inlined.]
</dd><dt><span class="term"><code class="literal">set(<em class="replaceable"><code>FieldPattern</code></em>)</code></span></dt><dd>
Picks out each field set join point whose signature matches
<em class="replaceable"><code>FieldPattern</code></em>.
[Note that the initializations of constant fields (static
final fields where the initializer is a constant string object or
primitive value) are not join points, since Java requires their
references to be inlined.]
</dd><dt><span class="term"><code class="literal">call(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></span></dt><dd>
Picks out each constructor call join point whose signature matches
<em class="replaceable"><code>ConstructorPattern</code></em>.
</dd><dt><span class="term"><code class="literal">execution(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></span></dt><dd>
Picks out each constructor execution join point whose signature matches
<em class="replaceable"><code>ConstructorPattern</code></em>.
</dd><dt><span class="term"><code class="literal">initialization(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></span></dt><dd>
Picks out each object initialization join point whose signature matches
<em class="replaceable"><code>ConstructorPattern</code></em>.
</dd><dt><span class="term"><code class="literal">preinitialization(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></span></dt><dd>
Picks out each object pre-initialization join point whose signature matches
<em class="replaceable"><code>ConstructorPattern</code></em>.
</dd><dt><span class="term"><code class="literal">staticinitialization(<em class="replaceable"><code>TypePattern</code></em>)</code></span></dt><dd>
Picks out each static initializer execution join point whose signature matches
<em class="replaceable"><code>TypePattern</code></em>.
</dd><dt><span class="term"><code class="literal">handler(<em class="replaceable"><code>TypePattern</code></em>)</code></span></dt><dd>
Picks out each exception handler join point whose signature matches
<em class="replaceable"><code>TypePattern</code></em>.
</dd><dt><span class="term"><code class="literal">adviceexecution()</code></span></dt><dd>
Picks out all advice execution join points.
</dd><dt><span class="term"><code class="literal">within(<em class="replaceable"><code>TypePattern</code></em>)</code></span></dt><dd>
Picks out each join point where the executing code is defined
in a type matched by <em class="replaceable"><code>TypePattern</code></em>.
</dd><dt><span class="term"><code class="literal">withincode(<em class="replaceable"><code>MethodPattern</code></em>)</code></span></dt><dd>
Picks out each join point where the executing code is defined in
a method whose signature matches
<em class="replaceable"><code>MethodPattern</code></em>.
</dd><dt><span class="term"><code class="literal">withincode(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></span></dt><dd>
Picks out each join point where the executing code is defined
in a constructor whose signature matches
<em class="replaceable"><code>ConstructorPattern</code></em>.
</dd><dt><span class="term"><code class="literal">cflow(<em class="replaceable"><code>Pointcut</code></em>)</code></span></dt><dd>
Picks out each join point in the control flow of any join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>, including
<em class="replaceable"><code>P</code></em> itself.
</dd><dt><span class="term"><code class="literal">cflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code></span></dt><dd>
Picks out each join point in the control flow of any join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>, but not
<em class="replaceable"><code>P</code></em> itself.
</dd><dt><span class="term"><code class="literal">this(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code></span></dt><dd>
Picks out each join point where the currently executing object
(the object bound to <code class="literal">this</code>) is an instance of
<em class="replaceable"><code>Type</code></em>, or of the type of the
identifier <em class="replaceable"><code>Id</code></em> (which must be bound in the enclosing
advice or pointcut definition).
Will not match any join points from static contexts.
</dd><dt><span class="term"><code class="literal">target(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code></span></dt><dd>
Picks out each join point where the target object (the object
on which a call or field operation is applied to) is an instance of
<em class="replaceable"><code>Type</code></em>, or of the type of the identifier
<em class="replaceable"><code>Id</code></em> (which must be bound in the enclosing
advice or pointcut definition).
Will not match any calls, gets, or sets of static members.
</dd><dt><span class="term"><code class="literal">args(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>, ...)</code></span></dt><dd>
Picks out each join point where the arguments are instances of
the appropriate type (or type of the identifier if using that form). A
<code class="literal">null</code> argument is matched iff the static type of the
argument (declared parameter type or field type) is the same as, or a subtype of,
the specified args type.
</dd><dt><span class="term"><code class="literal"><em class="replaceable"><code>PointcutId</code></em>(<em class="replaceable"><code>TypePattern</code></em> or <em class="replaceable"><code>Id</code></em>, ...)</code></span></dt><dd>
Picks out each join point that is picked out by the
user-defined pointcut designator named by
<em class="replaceable"><code>PointcutId</code></em>.
</dd><dt><span class="term"><code class="literal">if(<em class="replaceable"><code>BooleanExpression</code></em>)</code></span></dt><dd>
Picks out each join point where the boolean expression
evaluates to <code class="literal">true</code>. The boolean expression used
can only access static members, parameters exposed by the enclosing
pointcut or advice, and <code class="literal">thisJoinPoint</code> forms. In
particular, it cannot call non-static methods on the aspect or
use return values or exceptions exposed by after advice.
</dd><dt><span class="term"><code class="literal">! <em class="replaceable"><code>Pointcut</code></em></code></span></dt><dd>
Picks out each join point that is not picked out by
<em class="replaceable"><code>Pointcut</code></em>.
</dd><dt><span class="term"><code class="literal"><em class="replaceable"><code>Pointcut0</code></em> && <em class="replaceable"><code>Pointcut1</code></em></code></span></dt><dd>
Picks out each join points that is picked out by both
<em class="replaceable"><code>Pointcut0</code></em> and
<em class="replaceable"><code>Pointcut1</code></em>.
</dd><dt><span class="term"><code class="literal"><em class="replaceable"><code>Pointcut0</code></em> || <em class="replaceable"><code>Pointcut1</code></em></code></span></dt><dd>
Picks out each join point that is picked out by either
pointcuts. <em class="replaceable"><code>Pointcut0</code></em> or
<em class="replaceable"><code>Pointcut1</code></em>.
</dd><dt><span class="term"><code class="literal">( <em class="replaceable"><code>Pointcut</code></em> )</code></span></dt><dd>
Picks out each join points picked out by
<em class="replaceable"><code>Pointcut</code></em>.
</dd></dl></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pointcut-definition"></a>Pointcut definition</h3></div></div></div><p>
Pointcuts are defined and named by the programmer with the
<code class="literal">pointcut</code> declaration.
</p><pre class="programlisting">
pointcut publicIntCall(int i):
call(public * *(int)) && args(i);
</pre><p>
A named pointcut may be defined in either a class or aspect, and is
treated as a member of the class or aspect where it is found. As a
member, it may have an access modifier such as
<code class="literal">public</code> or <code class="literal">private</code>.
</p><pre class="programlisting">
class C {
pointcut publicCall(int i):
call(public * *(int)) && args(i);
}
class D {
pointcut myPublicCall(int i):
C.publicCall(i) && within(SomeType);
}
</pre><p>
Pointcuts that are not final may be declared abstract, and defined
without a body. Abstract pointcuts may only be declared within
abstract aspects.
</p><pre class="programlisting">
abstract aspect A {
abstract pointcut publicCall(int i);
}
</pre><p>
In such a case, an extending aspect may override the abstract
pointcut.
</p><pre class="programlisting">
aspect B extends A {
pointcut publicCall(int i): call(public Foo.m(int)) && args(i);
}
</pre><p>
For completeness, a pointcut with a declaration may be declared
<code class="literal">final</code>.
</p><p>
Though named pointcut declarations appear somewhat like method
declarations, and can be overridden in subaspects, they cannot be
overloaded. It is an error for two pointcuts to be named with the
same name in the same class or aspect declaration.
</p><p>
The scope of a named pointcut is the enclosing class declaration.
This is different than the scope of other members; the scope of
other members is the enclosing class <span class="emphasis"><em>body</em></span>.
This means that the following code is legal:
</p><pre class="programlisting">
aspect B percflow(publicCall()) {
pointcut publicCall(): call(public Foo.m(int));
}
</pre></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="context-exposure"></a>Context exposure</h3></div></div></div><p>
Pointcuts have an interface; they expose some parts of the
execution context of the join points they pick out. For example,
the PublicIntCall above exposes the first argument from the
receptions of all public unary integer methods. This context is
exposed by providing typed formal parameters to named pointcuts and
advice, like the formal parameters of a Java method. These formal
parameters are bound by name matching.
</p><p>
On the right-hand side of advice or pointcut declarations, in
certain pointcut designators, a Java identifier is allowed in place
of a type or collection of types. The pointcut designators that
allow this are <code class="literal">this</code>, <code class="literal">target</code>,
and <code class="literal">args</code>. In all such cases, using an
identifier rather than a type does two things. First, it selects
join points as based on the type of the formal parameter. So the
pointcut
</p><pre class="programlisting">
pointcut intArg(int i): args(i);
</pre><p>
picks out join points where an <code class="literal">int</code> (or
a <code class="literal">byte</code>, <code class="literal">short</code>, or
<code class="literal">char</code>; anything assignable to an
<code class="literal">int</code>) is being passed as an argument.
Second, though, it makes the value of that argument
available to the enclosing advice or pointcut.
</p><p>
Values can be exposed from named pointcuts as well, so
</p><pre class="programlisting">
pointcut publicCall(int x): call(public *.*(int)) && intArg(x);
pointcut intArg(int i): args(i);
</pre><p>
is a legal way to pick out all calls to public methods accepting an
int argument, and exposing that argument.
</p><p>
There is one special case for this kind of exposure. Exposing an
argument of type Object will also match primitive typed arguments,
and expose a "boxed" version of the primitive. So,
</p><pre class="programlisting">
pointcut publicCall(): call(public *.*(..)) && args(Object);
</pre><p>
will pick out all unary methods that take, as their only argument,
subtypes of Object (i.e., not primitive types like
<code class="literal">int</code>), but
</p><pre class="programlisting">
pointcut publicCall(Object o): call(public *.*(..)) && args(o);
</pre><p>
will pick out all unary methods that take any argument: And if the
argument was an <code class="literal">int</code>, then the value passed to
advice will be of type <code class="literal">java.lang.Integer</code>.
</p><p>
The "boxing" of the primitive value is based on the
<span class="emphasis"><em>original</em></span> primitive type. So in the
following program
</p><pre class="programlisting">
public class InstanceOf {
public static void main(String[] args) {
doInt(5);
}
static void doInt(int i) { }
}
aspect IntToLong {
pointcut el(long l) :
execution(* doInt(..)) && args(l);
before(Object o) : el(o) {
System.out.println(o.getClass());
}
}
</pre><p>
The pointcut will match and expose the integer argument,
but it will expose it as an <code class="literal">Integer</code>,
not a <code class="literal">Long</code>.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="primitive-pointcuts"></a>Primitive pointcuts</h3></div></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2326"></a>Method-related pointcuts</h4></div></div></div><p>AspectJ provides two primitive pointcut designators designed to
capture method call and execution join points. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">call(<em class="replaceable"><code>MethodPattern</code></em>)</code></li><li class="listitem"><code class="literal">execution(<em class="replaceable"><code>MethodPattern</code></em>)</code></li></ul></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2336"></a>Field-related pointcuts</h4></div></div></div><p>
AspectJ provides two primitive pointcut designators designed to
capture field reference and set join points:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">get(<em class="replaceable"><code>FieldPattern</code></em>)</code></li><li class="listitem"><code class="literal">set(<em class="replaceable"><code>FieldPattern</code></em>)</code></li></ul></div><p>
All set join points are treated as having one argument, the value the
field is being set to, so at a set join point, that value can be
accessed with an <code class="literal">args</code> pointcut. So an aspect
guarding a static integer variable x declared in type T might be written as
</p><pre class="programlisting">
aspect GuardedX {
static final int MAX_CHANGE = 100;
before(int newval): set(static int T.x) && args(newval) {
if (Math.abs(newval - T.x) > MAX_CHANGE)
throw new RuntimeException();
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2349"></a>Object creation-related pointcuts</h4></div></div></div><p>
AspectJ provides primitive pointcut designators designed to
capture the initializer execution join points of objects.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">call(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></li><li class="listitem"><code class="literal">execution(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></li><li class="listitem"><code class="literal">initialization(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></li><li class="listitem"><code class="literal">preinitialization(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></li></ul></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2365"></a>Class initialization-related pointcuts</h4></div></div></div><p>
AspectJ provides one primitive pointcut designator to pick out
static initializer execution join points.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">staticinitialization(<em class="replaceable"><code>TypePattern</code></em>)</code></li></ul></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2372"></a>Exception handler execution-related pointcuts</h4></div></div></div><p>
AspectJ provides one primitive pointcut designator to capture
execution of exception handlers:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">handler(<em class="replaceable"><code>TypePattern</code></em>)</code></li></ul></div><p>
All handler join points are treated as having one argument, the value
of the exception being handled. That value can be accessed with an
<code class="literal">args</code> pointcut. So an aspect used to put
<code class="literal">FooException</code> objects into some normal form before
they are handled could be written as
</p><pre class="programlisting">
aspect NormalizeFooException {
before(FooException e): handler(FooException) && args(e) {
e.normalize();
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2383"></a>Advice execution-related pointcuts</h4></div></div></div><p>
AspectJ provides one primitive pointcut designator to capture
execution of advice
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">adviceexecution()</code></li></ul></div><p>
This can be used, for example, to filter out any join point in the
control flow of advice from a particular aspect.
</p><pre class="programlisting">
aspect TraceStuff {
pointcut myAdvice(): adviceexecution() && within(TraceStuff);
before(): call(* *(..)) && !cflow(myAdvice) {
// do something
}
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2391"></a>State-based pointcuts</h4></div></div></div><p>
Many concerns cut across the dynamic times when an object of a
particular type is executing, being operated on, or being passed
around. AspectJ provides primitive pointcuts that capture join
points at these times. These pointcuts use the dynamic types of
their objects to pick out join points. They may also be used to
expose the objects used for discrimination.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">this(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code></li><li class="listitem"><code class="literal">target(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em>)</code></li></ul></div><p>
The <code class="literal">this</code> pointcut picks out each join point where
the currently executing object (the object bound to
<code class="literal">this</code>) is an instance of a particular type. The
<code class="literal">target</code> pointcut picks out each join point where
the target object (the object on which a method is called or a field
is accessed) is an instance of a particular type. Note that
<code class="literal">target</code> should be understood to be the object the
current join point is transfering control to. This means that the
target object is the same as the current object at a method execution
join point, for example, but may be different at a method call join
point.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">args(<em class="replaceable"><code>Type</code></em> or <em class="replaceable"><code>Id</code></em> or "..", ...)</code></li></ul></div><p>
The args pointcut picks out each join point where the arguments are
instances of some types. Each element in the comma-separated list is
one of four things. If it is a type name, then the argument in that
position must be an instance of that type. If it is an identifier,
then that identifier must be bound in the enclosing advice or
pointcut declaration, and so the argument in that position must be an
instance of the type of the identifier (or of any type if the
identifier is typed to Object). If it is the "*" wildcard, then any
argument will match, and if it is the special wildcard "..", then any
number of arguments will match, just like in signature patterns. So the
pointcut
</p><pre class="programlisting">
args(int, .., String)
</pre><p>
will pick out all join points where the first argument is an
<code class="literal">int</code> and the last is a <code class="literal">String</code>.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2418"></a>Control flow-based pointcuts</h4></div></div></div><p>
Some concerns cut across the control flow of the program. The
<code class="literal">cflow</code> and <code class="literal">cflowbelow</code> primitive
pointcut designators capture join points based on control flow.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">cflow(<em class="replaceable"><code>Pointcut</code></em>)</code></li><li class="listitem"><code class="literal">cflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code></li></ul></div><p>
The <code class="literal">cflow</code> pointcut picks out all join points that
occur between entry and exit of each join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>, including
<em class="replaceable"><code>P</code></em> itself. Hence, it picks out the join
points <span class="emphasis"><em>in</em></span> the control flow of the join points
picked out by <em class="replaceable"><code>Pointcut</code></em>.
</p><p>
The <code class="literal">cflowbelow</code> pointcut picks out all join points
that occur between entry and exit of each join point
<em class="replaceable"><code>P</code></em> picked out by
<em class="replaceable"><code>Pointcut</code></em>, but not including
<em class="replaceable"><code>P</code></em> itself. Hence, it picks out the join
points <span class="emphasis"><em>below</em></span> the control flow of the join points
picked out by <em class="replaceable"><code>Pointcut</code></em>.
</p><div class="sect4"><div class="titlepage"><div><div><h5 class="title"><a name="idm2444"></a>Context exposure from control flows</h5></div></div></div><p>
The <code class="literal">cflow</code> and
<code class="literal">cflowbelow</code> pointcuts may expose context
state through enclosed <code class="literal">this</code>,
<code class="literal">target</code>, and <code class="literal">args</code>
pointcuts.
</p><p>
Anytime such state is accessed, it is accessed through the
<span class="emphasis"><em>most recent</em></span> control flow that
matched. So the "current arg" that would be printed by
the following program is zero, even though it is in many
control flows.
</p><pre class="programlisting">
class Test {
public static void main(String[] args) {
fact(5);
}
static int fact(int x) {
if (x == 0) {
System.err.println("bottoming out");
return 1;
}
else return x * fact(x - 1);
}
}
aspect A {
pointcut entry(int i): call(int fact(int)) && args(i);
pointcut writing(): call(void println(String)) && ! within(A);
before(int i): writing() && cflow(entry(i)) {
System.err.println("Current arg is " + i);
}
}
</pre><p>
It is an error to expose such state through
<span class="emphasis"><em>negated</em></span> control flow pointcuts, such
as within <code class="literal">!
cflowbelow(<em class="replaceable"><code>P</code></em>)</code>.
</p></div></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2459"></a>Program text-based pointcuts</h4></div></div></div><p>
While many concerns cut across the runtime structure of the program,
some must deal with the lexical structure. AspectJ allows aspects to
pick out join points based on where their associated code is defined.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">within(<em class="replaceable"><code>TypePattern</code></em>)</code></li><li class="listitem"><code class="literal">withincode(<em class="replaceable"><code>MethodPattern</code></em>)</code></li><li class="listitem"><code class="literal">withincode(<em class="replaceable"><code>ConstructorPattern</code></em>)</code></li></ul></div><p>
The <code class="literal">within</code> pointcut picks out each join point
where the code executing is defined in the declaration of one of the
types in <em class="replaceable"><code>TypePattern</code></em>. This includes the
class initialization, object initialization, and method and
constructor execution join points for the type, as well as any join
points associated with the statements and expressions of the type.
It also includes any join points that are associated with code in a
type's nested types, and that type's default constructor, if there is
one.
</p><p>
The <code class="literal">withincode</code> pointcuts picks out each join point
where the code executing is defined in the declaration of a
particular method or constructor. This includes the method or
constructor execution join point as well as any join points
associated with the statements and expressions of the method or
constructor. It also includes any join points that are associated
with code in a method or constructor's local or anonymous types.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2477"></a>Expression-based pointcuts</h4></div></div></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">if(<em class="replaceable"><code>BooleanExpression</code></em>)</code></li></ul></div><p>
The if pointcut picks out join points based on a dynamic property.
its syntax takes an expression, which must evaluate to a boolean
true or false. Within this expression, the
<code class="literal">thisJoinPoint</code> object is available. So one
(extremely inefficient) way of picking out all call join points would
be to use the pointcut
</p><pre class="programlisting">
if(thisJoinPoint.getKind().equals("call"))
</pre><p>
Note that the order of evaluation for pointcut expression
components at a join point is undefined. Writing <code class="literal">if</code>
pointcuts that have side-effects is considered bad style and may also
lead to potentially confusing or even changing behavior with regard
to when or if the test code will run.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="signatures"></a>Signatures</h3></div></div></div><p>
One very important property of a join point is its signature, which is
used by many of AspectJ's pointcut designators to select particular
join points.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2491"></a>Methods</h4></div></div></div><p>
Join points associated with methods typically have method signatures,
consisting of a method name, parameter types, return type, the types of
the declared (checked) exceptions, and some type that the method could
be called on (below called the "qualifying type").
</p><p>
At a method call join point, the signature is a method signature whose
qualifying type is the static type used to <span class="emphasis"><em>access</em></span>
the method. This means that the signature for the join point created
from the call <code class="literal">((Integer)i).toString()</code> is different
than that for the call <code class="literal">((Object)i).toString()</code>, even
if <code class="literal">i</code> is the same variable.
</p><p>
At a method execution join point, the signature is a method signature
whose qualifying type is the declaring type of the method.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2500"></a>Fields</h4></div></div></div><p>
Join points associated with fields typically have field signatures,
consisting of a field name and a field type. A field reference join
point has such a signature, and no parameters. A field set join point
has such a signature, but has a has a single parameter whose type is
the same as the field type.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2503"></a>Constructors</h4></div></div></div><p>
Join points associated with constructors typically have constructor
signatures, consisting of a parameter types, the types of the declared
(checked) exceptions, and the declaring type.
</p><p>
At a constructor call join point, the signature is the constructor
signature of the called constructor. At a constructor execution join
point, the signature is the constructor signature of the currently
executing constructor.
</p><p>
At object initialization and pre-initialization join points, the
signature is the constructor signature for the constructor that started
this initialization: the first constructor entered during this type's
initialization of this object.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2508"></a>Others</h4></div></div></div><p>
At a handler execution join point, the signature is composed of the
exception type that the handler handles.
</p><p>
At an advice execution join point, the signature is composed of the
aspect type, the parameter types of the advice, the return type (void
for all but around advice) and the types of the declared (checked)
exceptions.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="matching"></a>Matching</h3></div></div></div><p>
The <code class="literal">withincode</code>, <code class="literal">call</code>,
<code class="literal">execution</code>, <code class="literal">get</code>, and
<code class="literal">set</code> primitive pointcut designators all use signature
patterns to determine the join points they describe. A signature
pattern is an abstract description of one or more join-point
signatures. Signature patterns are intended to match very closely the
same kind of things one would write when declaring individual members
and constructors.
</p><p>
Method declarations in Java include method names, method parameters,
return types, modifiers like static or private, and throws clauses,
while constructor declarations omit the return type and replace the
method name with the class name. The start of a particular method
declaration, in class <code class="literal">Test</code>, for example, might be
</p><pre class="programlisting">
class C {
public final void foo() throws ArrayOutOfBoundsException { ... }
}
</pre><p>
In AspectJ, method signature patterns have all these, but most elements
can be replaced by wildcards. So
</p><pre class="programlisting">
call(public final void C.foo() throws ArrayOutOfBoundsException)
</pre><p>
picks out call join points to that method, and the pointcut
</p><pre class="programlisting">
call(public final void *.*() throws ArrayOutOfBoundsException)
</pre><p>
picks out all call join points to methods, regardless of their name
name or which class they are defined on, so long as they take no
arguments, return no value, are both <code class="literal">public</code> and
<code class="literal">final</code>, and are declared to throw
<code class="literal">ArrayOutOfBounds</code> exceptions.
</p><p>
The defining type name, if not present, defaults to *, so another way
of writing that pointcut would be
</p><pre class="programlisting">
call(public final void *() throws ArrayOutOfBoundsException)
</pre><p>
The wildcard <code class="literal">..</code> indicates zero or more
parameters, so
</p><pre class="programlisting">
execution(void m(..))
</pre><p>
picks out execution join points for void methods named
<code class="literal">m</code>, of any number of arguments, while
</p><pre class="programlisting">
execution(void m(.., int))
</pre><p>
picks out execution join points for void methods named
<code class="literal">m</code> whose last parameter is of type
<code class="literal">int</code>.
</p><p>
The modifiers also form part of the signature pattern. If an AspectJ
signature pattern should match methods without a particular modifier,
such as all non-public methods, the appropriate modifier should be
negated with the <code class="literal">!</code> operator. So,
</p><pre class="programlisting">
withincode(!public void foo())
</pre><p>
picks out all join points associated with code in null non-public
void methods named <code class="literal">foo</code>, while
</p><pre class="programlisting">
withincode(void foo())
</pre><p>
picks out all join points associated with code in null void methods
named <code class="literal">foo</code>, regardless of access modifier.
</p><p>
Method names may contain the * wildcard, indicating any number of
characters in the method name. So
</p><pre class="programlisting">
call(int *())
</pre><p>
picks out all call join points to <code class="literal">int</code> methods
regardless of name, but
</p><pre class="programlisting">
call(int get*())
</pre><p>
picks out all call join points to <code class="literal">int</code> methods
where the method name starts with the characters "get".
</p><p>
AspectJ uses the <code class="literal">new</code> keyword for constructor
signature patterns rather than using a particular class name. So the
execution join points of private null constructor of a class C
defined to throw an ArithmeticException can be picked out with
</p><pre class="programlisting">
execution(private C.new() throws ArithmeticException)
</pre><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2560"></a>Matching based on the declaring type</h4></div></div></div><p>
The signature-matching pointcuts all specify a declaring type,
but the meaning varies slightly for each join point signature,
in line with Java semantics.
</p><p>
When matching for pointcuts <code class="literal">withincode</code>,
<code class="literal">get</code>, and <code class="literal">set</code>, the declaring
type is the class that contains the declaration.
</p><p>
When matching method-call join points, the
declaring type is the static type used to access the method.
A common mistake is to specify a declaring type for the
<code class="literal">call</code> pointcut that is a subtype of the
originally-declaring type. For example, given the class
</p><pre class="programlisting">
class Service implements Runnable {
public void run() { ... }
}
</pre><p>
the following pointcut
</p><pre class="programlisting">
call(void Service.run())
</pre><p>
would fail to pick out the join point for the code
</p><pre class="programlisting">
((Runnable) new Service()).run();
</pre><p>
Specifying the originally-declaring type is correct, but would
pick out any such call (here, calls to the <code class="literal">run()</code>
method of any Runnable).
In this situation, consider instead picking out the target type:
</p><pre class="programlisting">
call(void run()) && target(Service)
</pre><p>
When matching method-execution join points,
if the execution pointcut method signature specifies a declaring type,
the pointcut will only match methods declared in that type, or methods
that override methods declared in or inherited by that type.
So the pointcut
</p><pre class="programlisting">
execution(public void Middle.*())
</pre><p>
picks out all method executions for public methods returning void
and having no arguments that are either declared in, or inherited by,
Middle, even if those methods are overridden in a subclass of Middle.
So the pointcut would pick out the method-execution join point
for Sub.m() in this code:
</p><pre class="programlisting">
class Super {
protected void m() { ... }
}
class Middle extends Super {
}
class Sub extends Middle {
public void m() { ... }
}
</pre></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2581"></a>Matching based on the throws clause</h4></div></div></div><p>
Type patterns may be used to pick out methods and constructors
based on their throws clauses. This allows the following two
kinds of extremely wildcarded pointcuts:
</p><pre class="programlisting">
pointcut throwsMathlike():
// each call to a method with a throws clause containing at least
// one exception exception with "Math" in its name.
call(* *(..) throws *..*Math*);
pointcut doesNotThrowMathlike():
// each call to a method with a throws clause containing no
// exceptions with "Math" in its name.
call(* *(..) throws !*..*Math*);
</pre><p>
A <em class="replaceable"><code>ThrowsClausePattern</code></em> is a comma-separated list of
<em class="replaceable"><code>ThrowsClausePatternItem</code></em>s, where
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><em class="replaceable"><code>ThrowsClausePatternItem</code></em> :</span></dt><dd><code class="literal">[ ! ]
<em class="replaceable"><code>TypeNamePattern</code></em></code></dd></dl></div><p>
</p><p>
A <em class="replaceable"><code>ThrowsClausePattern</code></em> matches the
throws clause of any code member signature. To match, each
<code class="literal">ThrowsClausePatternItem</code> must
match the throws clause of the member in question. If any item
doesn't match, then the whole pattern doesn't match.
</p><p>
If a ThrowsClausePatternItem begins with "!", then it matches a
particular throws clause if and only if <span class="emphasis"><em>none</em></span>
of the types named in the throws clause is matched by the
<code class="literal">TypeNamePattern</code>.
</p><p>
If a <em class="replaceable"><code>ThrowsClausePatternItem</code></em> does not
begin with "!", then it matches a throws clause if and only if
<span class="emphasis"><em>any</em></span> of the types named in the throws clause
is matched by the <span class="emphasis"><em>TypeNamePattern</em></span>.
</p><p>
The rule for "!" matching has one potentially surprising
property, in that these two pointcuts
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> call(* *(..) throws !IOException) </li><li class="listitem"> call(* *(..) throws (!IOException)) </li></ul></div><p>
will match differently on calls to
</p><div class="blockquote"><blockquote class="blockquote"><code class="literal">
void m() throws RuntimeException, IOException {}
</code></blockquote></div><p>
</p><p>
[1] will NOT match the method m(), because method m's throws
clause declares that it throws IOException. [2] WILL match the
method m(), because method m's throws clause declares the it
throws some exception which does not match IOException,
i.e. RuntimeException.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="type-patterns"></a>Type patterns</h3></div></div></div><p>
Type patterns are a way to pick out collections of types and use them
in places where you would otherwise use only one type. The rules for
using type patterns are simple.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2615"></a>Exact type pattern</h4></div></div></div><p>
First, all type names are also type patterns. So
<code class="literal">Object</code>, <code class="literal">java.util.HashMap</code>,
<code class="literal">Map.Entry</code>, <code class="literal">int</code> are all type
patterns.
</p><p>
If a type pattern is an exact type - if it doesn't
include a wildcard - then the matching works just
like normal type lookup in Java: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">Patterns that have the same names as
primitive types (like <code class="literal">int</code>) match
those primitive types.</li><li class="listitem">Patterns that are qualified by package names
(like <code class="literal">java.util.HashMap</code>) match types
in other packages.
</li><li class="listitem">Patterns that are not qualified (like
<code class="literal">HashMap</code>) match types that are
resolved by Java's normal scope rules. So, for
example, <code class="literal">HashMap</code> might match a
package-level type in the same package or a type that
have been imported with java's
<code class="literal">import</code> form. But it would not match
<code class="literal">java.util.HashMap</code> unless the aspect
were in <code class="literal">java.util</code> or the type had
been imported.
</li></ul></div><p>
So exact type patterns match based on usual Java scope
rules.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2635"></a>Type name patterns</h4></div></div></div><p>
There is a special type name, *, which is also a type pattern. * picks out all
types, including primitive types. So
</p><pre class="programlisting">
call(void foo(*))
</pre><p>
picks out all call join points to void methods named foo, taking one
argument of any type.
</p><p>
Type names that contain the two wildcards "*" and
"<code class="literal">..</code>" are also type patterns. The * wildcard matches
zero or more characters characters except for ".", so it can be used
when types have a certain naming convention. So
</p><pre class="programlisting">
handler(java.util.*Map)
</pre><p>
picks out the types java.util.Map and java.util.java.util.HashMap,
among others, and
</p><pre class="programlisting">
handler(java.util.*)
</pre><p>
picks out all types that start with "<code class="literal">java.util.</code>" and
don't have any more "."s, that is, the types in the
<code class="literal">java.util</code> package, but not inner types
(such as java.util.Map.Entry).
</p><p>
The "<code class="literal">..</code>" wildcard matches any sequence of
characters that start and end with a ".", so it can be used
to pick out all types in any subpackage, or all inner types. So
</p><pre class="programlisting">
within(com.xerox..*)
</pre><p>
picks out all join points where the code is in any
declaration of a type whose name begins with "<code class="literal">com.xerox.</code>".
</p><p>
Type patterns with wildcards do not depend on Java's
usual scope rules - they match against all types
available to the weaver, not just those that are
imported into an Aspect's declaring file.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2654"></a>Subtype patterns</h4></div></div></div><p>
It is possible to pick out all subtypes of a type (or a collection of
types) with the "+" wildcard. The "+" wildcard follows immediately a
type name pattern. So, while
</p><pre class="programlisting">
call(Foo.new())
</pre><p>
picks out all constructor call join points where an instance of exactly
type Foo is constructed,
</p><pre class="programlisting">
call(Foo+.new())
</pre><p>
picks out all constructor call join points where an instance of any
subtype of Foo (including Foo itself) is constructed, and the unlikely
</p><pre class="programlisting">
call(*Handler+.new())
</pre><p>
picks out all constructor call join points where an instance of any
subtype of any type whose name ends in "Handler" is constructed.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2663"></a>Array type patterns</h4></div></div></div><p>
A type name pattern or subtype pattern can be followed by one or more
sets of square brackets to make array type patterns. So
<code class="literal">Object[]</code> is an array type pattern, and so is
<code class="literal">com.xerox..*[][]</code>, and so is
<code class="literal">Object+[]</code>.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2669"></a>Type patterns</h4></div></div></div><p>
Type patterns are built up out of type name patterns, subtype patterns,
and array type patterns, and constructed with boolean operators
<code class="literal">&&</code>, <code class="literal">||</code>, and
<code class="literal">!</code>. So
</p><pre class="programlisting">
staticinitialization(Foo || Bar)
</pre><p>
picks out the static initializer execution join points of either Foo or Bar,
and
</p><pre class="programlisting">
call((Foo+ && ! Foo).new(..))
</pre><p>
picks out the constructor call join points when a subtype of Foo, but
not Foo itself, is constructed.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="pattern-summary"></a>Pattern Summary</h3></div></div></div><p>
Here is a summary of the pattern syntax used in AspectJ:
</p><pre class="programlisting">
MethodPattern =
[ModifiersPattern] TypePattern
[TypePattern . ] IdPattern (TypePattern | ".." , ... )
[ throws ThrowsPattern ]
ConstructorPattern =
[ModifiersPattern ]
[TypePattern . ] new (TypePattern | ".." , ...)
[ throws ThrowsPattern ]
FieldPattern =
[ModifiersPattern] TypePattern [TypePattern . ] IdPattern
ThrowsPattern =
[ ! ] TypePattern , ...
TypePattern =
IdPattern [ + ] [ [] ... ]
| ! TypePattern
| TypePattern && TypePattern
| TypePattern || TypePattern
| ( TypePattern )
IdPattern =
Sequence of characters, possibly with special * and .. wildcards
ModifiersPattern =
[ ! ] JavaModifier ...
</pre></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-advice"></a>Advice</h2></div></div></div><p>
Each piece of advice is of the form
</p><div class="blockquote"><blockquote class="blockquote"><code class="literal">[ strictfp ] <em class="replaceable"><code>AdviceSpec</code></em> [
throws <em class="replaceable"><code>TypeList</code></em> ] :
<em class="replaceable"><code>Pointcut</code></em> {
<em class="replaceable"><code>Body</code></em> } </code></blockquote></div><p>
where <em class="replaceable"><code>AdviceSpec</code></em> is one of
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">before( <em class="replaceable"><code>Formals</code></em> ) </code></li><li class="listitem"><code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) returning
[ ( <em class="replaceable"><code>Formal</code></em> ) ] </code></li><li class="listitem"><code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) throwing [
( <em class="replaceable"><code>Formal</code></em> ) ] </code></li><li class="listitem"><code class="literal">after( <em class="replaceable"><code>Formals</code></em> ) </code></li><li class="listitem"><code class="literal"><em class="replaceable"><code>Type</code></em>
around( <em class="replaceable"><code>Formals</code></em> )</code></li></ul></div><p>
and where <em class="replaceable"><code>Formal</code></em> refers to a
variable binding like those used for method parameters,
of the form
<code class="literal"><em class="replaceable"><code>Type</code></em></code>
<code class="literal"><em class="replaceable"><code>Variable-Name</code></em></code>,
and <em class="replaceable"><code>Formals</code></em> refers to a comma-delimited
list of <em class="replaceable"><code>Formal</code></em>.
</p><p>
Advice defines crosscutting behavior. It is defined in terms of
pointcuts. The code of a piece of advice runs at every join point
picked out by its pointcut. Exactly how the code runs depends on the
kind of advice.
</p><p>
AspectJ supports three kinds of advice. The kind of advice determines how
it interacts with the join points it is defined over. Thus AspectJ
divides advice into that which runs before its join points, that which
runs after its join points, and that which runs in place of (or "around")
its join points.
</p><p>
While before advice is relatively unproblematic, there can be three
interpretations of after advice: After the execution of a join point
completes normally, after it throws an exception, or after it does either
one. AspectJ allows after advice for any of these situations.
</p><pre class="programlisting">
aspect A {
pointcut publicCall(): call(public Object *(..));
after() returning (Object o): publicCall() {
System.out.println("Returned normally with " + o);
}
after() throwing (Exception e): publicCall() {
System.out.println("Threw an exception: " + e);
}
after(): publicCall(){
System.out.println("Returned or threw an Exception");
}
}
</pre><p>
After returning advice may not care about its returned object, in which
case it may be written
</p><pre class="programlisting">
after() returning: call(public Object *(..)) {
System.out.println("Returned normally");
}
</pre><p>
If after returning does expose its returned object, then the
type of the parameter is considered to be an
<code class="literal">instanceof</code>-like constraint on the advice: it
will run only when the return value is of the appropriate type.
</p><p>
A value is of the appropriate type if it would be assignable to
a variable of that type, in the Java sense. That is, a
<code class="literal">byte</code> value is assignable to a
<code class="literal">short</code> parameter but not vice-versa, an
<code class="literal">int</code> is assignable to a
<code class="literal">float</code> parameter, <code class="literal">boolean</code>
values are only assignable to <code class="literal">boolean</code>
parameters, and reference types work by instanceof.
</p><p>
There are two special cases: If the exposed value is typed to
<code class="literal">Object</code>, then the advice is not constrained by
that type: the actual return value is converted to an object
type for the body of the advice: <code class="literal">int</code> values
are represented as <code class="literal">java.lang.Integer</code> objects,
etc, and no value (from void methods, for example) is
represented as <code class="literal">null</code>.
</p><p>
Secondly, the <code class="literal">null</code> value is assignable to a
parameter <code class="literal">T</code> if the join point
<span class="emphasis"><em>could</em></span> return something of type
<code class="literal">T</code>.
</p><p>
Around advice runs in place of the join point it operates over, rather
than before or after it. Because around is allowed to return a value, it
must be declared with a return type, like a method.
</p><p>
Thus, a simple use of around advice is to make a particular method
constant:
</p><pre class="programlisting">
aspect A {
int around(): call(int C.foo()) {
return 3;
}
}
</pre><p>
Within the body of around advice, though, the computation of the original
join point can be executed with the special syntax
</p><pre class="programlisting">
proceed( ... )
</pre><p>
The proceed form takes as arguments the context exposed by the around's
pointcut, and returns whatever the around is declared to return. So the
following around advice will double the second argument to
<code class="literal">foo</code> whenever it is called, and then halve its result:
</p><pre class="programlisting">
aspect A {
int around(int i): call(int C.foo(Object, int)) && args(i) {
int newi = proceed(i*2)
return newi/2;
}
}
</pre><p>
If the return value of around advice is typed to
<code class="literal">Object</code>, then the result of proceed is converted to an
object representation, even if it is originally a primitive value. And
when the advice returns an Object value, that value is converted back to
whatever representation it was originally. So another way to write the
doubling and halving advice is:
</p><pre class="programlisting">
aspect A {
Object around(int i): call(int C.foo(Object, int)) && args(i) {
Integer newi = (Integer) proceed(i*2)
return new Integer(newi.intValue() / 2);
}
}
</pre><p>
Any occurence of <code class="literal">proceed(..)</code> within the body of around
advice is treated as the special proceed form (even if the
aspect defines a method named <code class="literal">proceed</code>), unless a
target other than the aspect instance is specified as the recipient of
the call.
For example, in the following program the first
call to proceed will be treated as a method call to
the <code class="literal">ICanProceed</code> instance, whereas the second call to
proceed is treated as the special proceed form.
</p><pre class="programlisting">
aspect A {
Object around(ICanProceed canProceed) : execution(* *(..)) && this(canProceed) {
canProceed.proceed(); // a method call
return proceed(canProceed); // the special proceed form
}
private Object proceed(ICanProceed canProceed) {
// this method cannot be called from inside the body of around advice in
// the aspect
}
}
</pre><p>
In all kinds of advice, the parameters of the advice behave exactly like
method parameters. In particular, assigning to any parameter affects
only the value of the parameter, not the value that it came from. This
means that
</p><pre class="programlisting">
aspect A {
after() returning (int i): call(int C.foo()) {
i = i * 2;
}
}
</pre><p>
will <span class="emphasis"><em>not</em></span> double the returned value of the advice.
Rather, it will double the local parameter. Changing the values of
parameters or return values of join points can be done by using around
advice.
</p><p>
With <code class="literal">proceed(..)</code> it is possible to change the values
used by less-precedent advice and the underlying join point by supplying
different values for the variables. For example, this aspect replaces
the string bound to <code class="literal">s</code> in the named pointcut
<code class="literal">privateData</code>:
</p><pre class="programlisting">
aspect A {
Object around(String s): MyPointcuts.privateData(s) {
return proceed("private data");
}
}
</pre><p>
If you replace an argument to <code class="literal">proceed(..)</code>, you can cause
a <code class="literal">ClassCastException</code> at runtime when the argument
refers to a supertype of the actual type and you do not supply a
reference of the actual type. In the following aspect, the
around advice replaces the declared target <code class="literal">List</code>
with an <code class="literal">ArrayList</code>. This is valid code at
compile-time since the types match.
</p><pre class="programlisting">
import java.util.*;
aspect A {
Object around(List list): call(* List+.*()) && target(list) {
return proceed(new ArrayList());
}
}
</pre><p>
But imagine a simple program where the actual target is
<code class="literal">LinkedList</code>. In this case, the advice would cause a
<code class="literal">ClassCastException</code> at runtime, and
<code class="literal">peek()</code> is not declared in <code class="literal">ArrayList</code>.
</p><pre class="programlisting">
public class Test {
public static void main(String[] args) {
new LinkedList().peek();
}
}
</pre><p>
The <code class="literal">ClassCastException</code> can occur even in situations
where it appears to be unnecessary, e.g., if the program is changed to
call <code class="literal">size()</code>, declared in <code class="literal">List</code>:
</p><pre class="programlisting">
public class Test {
public static void main(String[] args) {
new LinkedList().size();
}
}
</pre><p>
There will still be a <code class="literal">ClassCastException</code> because
it is impossible to prove that there won't be a runtime binary-compatible
change in the hierarchy of <code class="literal">LinkedList</code> or some
other advice on the join point that requires a
<code class="literal">LinkedList</code>.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice-modifiers"></a>Advice modifiers</h3></div></div></div><p>
The <code class="literal">strictfp</code> modifier is the only modifier allowed
on advice, and it has the effect of making all floating-point
expressions within the advice be FP-strict.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice-and-checked-exceptions"></a>Advice and checked exceptions</h3></div></div></div><p>
An advice declaration must include a <code class="literal">throws</code> clause
listing the checked exceptions the body may throw. This list of
checked exceptions must be compatible with each target join point
of the advice, or an error is signalled by the compiler.
</p><p>
For example, in the following declarations:
</p><pre class="programlisting">
import java.io.FileNotFoundException;
class C {
int i;
int getI() { return i; }
}
aspect A {
before(): get(int C.i) {
throw new FileNotFoundException();
}
before() throws FileNotFoundException: get(int C.i) {
throw new FileNotFoundException();
}
}
</pre><p>
both pieces of advice are illegal. The first because the body throws
an undeclared checked exception, and the second because field get join
points cannot throw <code class="literal">FileNotFoundException</code>s.
</p><p> The exceptions that each kind of join point in AspectJ may throw are:
</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">method call and execution</span></dt><dd>
the checked exceptions declared by the target method's
<code class="literal">throws</code> clause.
</dd><dt><span class="term">constructor call and execution</span></dt><dd>
the checked exceptions declared by the target constructor's
<code class="literal">throws</code> clause.
</dd><dt><span class="term">field get and set</span></dt><dd>
no checked exceptions can be thrown from these join points.
</dd><dt><span class="term">exception handler execution</span></dt><dd>
the exceptions that can be thrown by the target exception handler.
</dd><dt><span class="term">static initializer execution</span></dt><dd>
no checked exceptions can be thrown from these join points.
</dd><dt><span class="term">pre-initialization and initialization</span></dt><dd>
any exception that is in the throws clause of
<span class="emphasis"><em>all</em></span> constructors of the initialized class.
</dd><dt><span class="term">advice execution</span></dt><dd>
any exception that is in the throws clause of the advice.
</dd></dl></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice-precedence"></a>Advice precedence</h3></div></div></div><p>
Multiple pieces of advice may apply to the same join point. In such
cases, the resolution order of the advice is based on advice
precedence.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2832"></a>Determining precedence</h4></div></div></div><p>There are a number of rules that determine whether a particular
piece of advice has precedence over another when they advise the same
join point. </p><p>If the two pieces of advice are defined in different aspects,
then there are three cases: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">If aspect A is matched earlier than aspect B in some
<code class="literal">declare precedence</code> form, then all advice in
concrete aspect A has precedence over all advice in concrete aspect B
when they are on the same join point. </li><li class="listitem">
Otherwise, if aspect A is a subaspect of aspect B, then all advice
defined in A has precedence over all advice defined in
B. So, unless otherwise specified with
<code class="literal">declare precedence</code>, advice in a subaspect
has precedence over advice in a superaspect.
</li><li class="listitem">
Otherwise, if two pieces of advice are defined in two different
aspects, it is undefined which one has precedence.
</li></ul></div><p>If the two pieces of advice are defined in the same aspect, then
there are two cases: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">If either are <code class="literal">after</code> advice, then the one that
appears later in the aspect has precedence over the one that appears
earlier. </li><li class="listitem">Otherwise, then the one that appears earlier in the aspect
has precedence over the one that appears later.
</li></ul></div><p>These rules can lead to circularity, such as</p><pre class="programlisting">
aspect A {
before(): execution(void main(String[] args)) {}
after(): execution(void main(String[] args)) {}
before(): execution(void main(String[] args)) {}
}
</pre><p>such circularities will result in errors signalled by the compiler. </p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm2850"></a>Effects of precedence</h4></div></div></div><p>At a particular join point, advice is ordered by precedence.</p><p>A piece of <code class="literal">around</code> advice controls whether
advice of lower precedence will run by calling
<code class="literal">proceed</code>. The call to <code class="literal">proceed</code>
will run the advice with next precedence, or the computation under the
join point if there is no further advice. </p><p>A piece of <code class="literal">before</code> advice can prevent advice of
lower precedence from running by throwing an exception. If it returns
normally, however, then the advice of the next precedence, or the
computation under the join pint if there is no further advice, will run.
</p><p>Running <code class="literal">after returning</code> advice will run the
advice of next precedence, or the computation under the join point if
there is no further advice. Then, if that computation returned
normally, the body of the advice will run. </p><p>Running <code class="literal">after throwing</code> advice will run the
advice of next precedence, or the computation under the join
point if there is no further advice. Then, if that computation threw
an exception of an appropriate type, the body of the advice will
run. </p><p>Running <code class="literal">after</code> advice will run the advice of
next precedence, or the computation under the join point if
there is no further advice. Then the body of the advice will
run. </p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="reflective-access-to-the-join-point"></a>Reflective access to the join point</h3></div></div></div><p>
Three special variables are visible within bodies of advice
and within <code class="literal">if()</code> pointcut expressions:
<code class="literal">thisJoinPoint</code>,
<code class="literal">thisJoinPointStaticPart</code>, and
<code class="literal">thisEnclosingJoinPointStaticPart</code>. Each is bound to
an object that encapsulates some of the context of the advice's current
or enclosing join point. These variables exist because some pointcuts
may pick out very large collections of join points. For example, the
pointcut
</p><pre class="programlisting">
pointcut publicCall(): call(public * *(..));
</pre><p>
picks out calls to many methods. Yet the body of advice over this
pointcut may wish to have access to the method name or parameters of a
particular join point.
</p><p>
<code class="literal">thisJoinPoint</code> is bound to a complete join point
object.
</p><p>
<code class="literal">thisJoinPointStaticPart</code> is bound to a part of the
join point object that includes less information, but for which no
memory allocation is required on each execution of the advice. It is
equivalent to <code class="literal">thisJoinPoint.getStaticPart()</code>.
</p><p>
<code class="literal">thisEnclosingJoinPointStaticPart</code> is bound to the
static part of the join point enclosing the current join point. Only
the static part of this enclosing join point is available through this
mechanism.
</p><p>
Standard Java reflection uses objects from the
<code class="literal">java.lang.reflect</code> hierarchy to build up its
reflective objects. Similarly, AspectJ join point objects have types
in a type hierarchy. The type of objects bound to
<code class="literal">thisJoinPoint</code> is
<code class="literal">org.aspectj.lang.JoinPoint</code>, while
<code class="literal">thisStaticJoinPoint</code> is bound to objects of interface
type <code class="literal">org.aspectj.lang.JoinPoint.StaticPart</code>.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-declare"></a>Static crosscutting</h2></div></div></div><p>
Advice declarations change the behavior of classes they crosscut, but do
not change their static type structure. For crosscutting concerns that do
operate over the static structure of type hierarchies, AspectJ provides
inter-type member declarations and other <code class="literal">declare</code> forms.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="inter-type-member-declarations"></a>Inter-type member declarations</h3></div></div></div><p>
AspectJ allows the declaration of members by aspects that are
associated with other types.
</p><p>
An inter-type method declaration looks like
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">
[ <em class="replaceable"><code>Modifiers</code></em> ]
<em class="replaceable"><code>Type</code></em> <em class="replaceable"><code>OnType</code></em>
.
<em class="replaceable"><code>Id</code></em>(<em class="replaceable"><code>Formals</code></em>)
[ <em class="replaceable"><code>ThrowsClause</code></em> ]
{ <em class="replaceable"><code>Body</code></em> }</code></li><li class="listitem"><code class="literal">abstract
[ <em class="replaceable"><code>Modifiers</code></em> ]
<em class="replaceable"><code>Type</code></em> <em class="replaceable"><code>OnType</code></em>
. <em class="replaceable"><code>Id</code></em>(<em class="replaceable"><code>Formals</code></em>)
[ <em class="replaceable"><code>ThrowsClause</code></em> ]
;
</code></li></ul></div><p>
The effect of such a declaration is to make <em class="replaceable"><code>OnType</code></em>
support the new method. Even if <em class="replaceable"><code>OnType</code></em> is
an interface. Even if the method is neither public nor abstract. So the
following is legal AspectJ code:
</p><pre class="programlisting">
interface Iface {}
aspect A {
private void Iface.m() {
System.err.println("I'm a private method on an interface");
}
void worksOnI(Iface iface) {
// calling a private method on an interface
iface.m();
}
}
</pre><p>
An inter-type constructor declaration looks like
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">
[ <em class="replaceable"><code>Modifiers</code></em> ]
<em class="replaceable"><code>OnType</code></em> . new (
<em class="replaceable"><code>Formals</code></em> )
[ <em class="replaceable"><code>ThrowsClause</code></em> ]
{ <em class="replaceable"><code>Body</code></em> }</code></li></ul></div><p>
The effect of such a declaration is to make
<em class="replaceable"><code>OnType</code></em> support the new constructor. It is
an error for <em class="replaceable"><code>OnType</code></em> to be an interface.
</p><p>
Inter-type declared constructors cannot be used to assign a
value to a final variable declared in <em class="replaceable"><code>OnType</code></em>.
This limitation significantly increases the ability to both understand
and compile the <em class="replaceable"><code>OnType</code></em> class and the
declaring aspect separately.
</p><p>
Note that in the Java language, classes that define no constructors
have an implicit no-argument constructor that just calls
<code class="literal">super()</code>. This means that attempting to declare
a no-argument inter-type constructor on such a class may result in
a conflict, even though it <span class="emphasis"><em>looks</em></span> like no
constructor is defined.
</p><p>
An inter-type field declaration looks like one of
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">
[ <em class="replaceable"><code>Modifiers</code></em> ]
<em class="replaceable"><code>Type</code></em>
<em class="replaceable"><code>OnType</code></em> . <em class="replaceable"><code>Id</code></em>
= <em class="replaceable"><code>Expression</code></em>;</code></li><li class="listitem"><code class="literal">
[ <em class="replaceable"><code>Modifiers</code></em> ]
<em class="replaceable"><code>Type</code></em>
<em class="replaceable"><code>OnType</code></em> . <em class="replaceable"><code>Id</code></em>;</code></li></ul></div><p>
The effect of such a declaration is to make
<em class="replaceable"><code>OnType</code></em> support the new field. Even if
<em class="replaceable"><code>OnType</code></em> is an interface. Even if the field is
neither public, nor static, nor final.
</p><p>
The initializer, if any, of an inter-type field declaration runs
before the class-local initializers defined in its target class.
</p></div><p>
Any occurrence of the identifier <code class="literal">this</code> in the body of
an inter-type constructor or method declaration, or in the initializer
of an inter-type field declaration, refers to the
<em class="replaceable"><code>OnType</code></em> object rather than to the aspect
type; it is an error to access <code class="literal">this</code> in such a
position from a <code class="literal">static</code> inter-type member
declaration.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="access-modifiers"></a>Access modifiers</h3></div></div></div><p>
Inter-type member declarations may be public or private, or have
default (package-protected) visibility. AspectJ does not provide
protected inter-type members.
</p><p>
The access modifier applies in relation to the aspect, not in relation
to the target type. So a private inter-type member is visible only from
code that is defined within the declaring aspect. A default-visibility
inter-type member is visible only from code that is defined within the
declaring aspect's package.
</p><p>
Note that a declaring a private inter-type method (which AspectJ
supports) is very different from inserting a private method declaration
into another class. The former allows access only from the declaring
aspect, while the latter would allow access only from the target type.
Java serialization, for example, uses the presense of a private method
<code class="literal">void writeObject(ObjectOutputStream)</code> for the
implementation of <code class="literal">java.io.Serializable</code>. A private
inter-type declaration of that method would not fulfill this
requirement, since it would be private to the aspect, not private to
the target type.
</p><p>
The access modifier of abstract inter-type methods has
one constraint: It is illegal to declare an abstract
non-public inter-type method on a public interface. This
is illegal because it would say that a public interface
has a constraint that only non-public implementors must
fulfill. This would not be compatible with Java's type
system.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="conflicts"></a>Conflicts</h3></div></div></div><p>
Inter-type declarations raise the possibility of conflicts among
locally declared members and inter-type members. For example, assuming
<code class="literal">otherPackage</code> is not the package containing the
aspect <code class="classname">A</code>, the code
</p><pre class="programlisting">
aspect A {
private Registry otherPackage.onType.r;
public void otherPackage.onType.register(Registry r) {
r.register(this);
this.r = r;
}
}
</pre><p>
declares that <code class="literal">onType</code> in <code class="literal">otherPackage</code> has a field
<code class="literal">r</code>. This field, however, is only accessible from the
code inside of aspect <code class="literal">A</code>. The aspect also declares
that <code class="literal">onType</code> has a method
"<code class="literal">register</code>", but makes this method accessible from
everywhere.
</p><p>
If <code class="literal">onType</code> already defines a
private or package-protected field "<code class="literal">r</code>", there is no
conflict: The aspect cannot see such a field, and no code in
<code class="literal">otherPackage</code> can see the inter-type
"<code class="literal">r</code>".
</p><p>
If <code class="literal">onType</code> defines a public field
"<code class="literal">r</code>", there is a conflict: The expression
</p><pre class="programlisting">
this.r = r
</pre><p>
is an error, since it is ambiguous whether the private inter-type
"<code class="literal">r</code>" or the public locally-defined
"<code class="literal">r</code>" should be used.
</p><p>
If <code class="literal">onType</code> defines a method
"<code class="literal">register(Registry)</code>" there is a conflict, since it
would be ambiguous to any code that could see such a defined method
which "<code class="literal">register(Registry)</code>" method was applicable.
</p><p>
Conflicts are resolved as much as possible as per Java's conflict
resolution rules:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">A subclass can inherit multiple <span class="emphasis"><em>fields</em></span> from its superclasses,
all with the same name and type. However, it is an error to have an ambiguous
<span class="emphasis"><em>reference</em></span> to a field.</li><li class="listitem">A subclass can only inherit multiple
<span class="emphasis"><em>methods</em></span> with the same name and argument types from
its superclasses if only zero or one of them is concrete (i.e., all but
one is abstract, or all are abstract).
</li></ul></div><p>
Given a potential conflict between inter-type member declarations in
different aspects, if one aspect has precedence over the other its
declaration will take effect without any conflict notice from compiler.
This is true both when the precedence is declared explicitly with
<code class="literal">declare precedence</code> as well as when when sub-aspects
implicitly have precedence over their super-aspect.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="extension-and-implementation"></a>Extension and Implementation</h3></div></div></div><p>
An aspect may change the inheritance hierarchy of a system by changing
the superclass of a type or adding a superinterface onto a type, with
the <code class="literal">declare parents</code> form.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">declare parents: <em class="replaceable"><code>TypePattern</code></em> extends <em class="replaceable"><code>Type</code></em>;</code></li><li class="listitem"><code class="literal">declare parents: <em class="replaceable"><code>TypePattern</code></em> implements <em class="replaceable"><code>TypeList</code></em>;</code></li></ul></div><p>
For example, if an aspect wished to make a particular class runnable,
it might define appropriate inter-type <code class="literal">void
run()</code> method, but it should also declare that the class
fulfills the <code class="literal">Runnable</code> interface. In order to
implement the methods in the <code class="literal">Runnable</code> interface, the
inter-type <code class="literal">run()</code> method must be public:
</p><pre class="programlisting">
aspect A {
declare parents: SomeClass implements Runnable;
public void SomeClass.run() { ... }
}
</pre></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="interfaces-with-members"></a>Interfaces with members</h3></div></div></div><p>
Through the use of inter-type members, interfaces may now carry
(non-public-static-final) fields and (non-public-abstract) methods that
classes can inherit. Conflicts may occur from ambiguously inheriting
members from a superclass and multiple superinterfaces.
</p><p>
Because interfaces may carry non-static initializers, each interface
behaves as if it has a zero-argument constructor containing its
initializers. The order of super-interface instantiation is
observable. We fix this order with the following properties: A
supertype is initialized before a subtype, initialized code runs only
once, and the initializers for a type's superclass are run before the
initializers for its superinterfaces. Consider the following hierarchy
where {<code class="literal">Object</code>, <code class="literal">C</code>,
<code class="literal">D</code>, <code class="literal">E</code>} are classes,
{<code class="literal">M</code>, <code class="literal">N</code>, <code class="literal">O</code>,
<code class="literal">P</code>, <code class="literal">Q</code>} are interfaces.
</p><pre class="programlisting">
Object M O
\ / \ /
C N Q
\ / /
D P
\ /
E
</pre><p>
when a new <code class="literal">E</code> is instantiated, the initializers run in this order:
</p><pre class="programlisting">
Object M C O N D Q P E
</pre></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="warnings-and-errors"></a>Warnings and Errors</h3></div></div></div><p>An aspect may specify that a particular join point should never be
reached. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">declare error: <em class="replaceable"><code>Pointcut</code></em>: <em class="replaceable"><code>String</code></em>;</code></li><li class="listitem"><code class="literal">declare warning: <em class="replaceable"><code>Pointcut</code></em>: <em class="replaceable"><code>String</code></em>;</code></li></ul></div><p>If the compiler determines that a join point in
<em class="replaceable"><code>Pointcut</code></em> could possibly be reached, then it
will signal either an error or warning, as declared, using the
<em class="replaceable"><code>String</code></em> for its message. </p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="softened-exceptions"></a>Softened exceptions</h3></div></div></div><p>An aspect may specify that a particular kind of exception, if
thrown at a join point, should bypass Java's usual static exception
checking system and instead be thrown as a
<code class="literal">org.aspectj.lang.SoftException</code>, which is subtype of
<code class="literal">RuntimeException</code> and thus does not need to be
declared. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">declare soft: <em class="replaceable"><code>Type</code></em>: <em class="replaceable"><code>Pointcut</code></em>;</code></li></ul></div><p>For example, the aspect</p><pre class="programlisting">
aspect A {
declare soft: Exception: execution(void main(String[] args));
}
</pre><p>Would, at the execution join point, catch any
<code class="literal">Exception</code> and rethrow a
<code class="literal">org.aspectj.lang.SoftException</code> containing
original exception. </p><p>This is similar to what the following advice would do</p><pre class="programlisting">
aspect A {
void around() execution(void main(String[] args)) {
try { proceed(); }
catch (Exception e) {
throw new org.aspectj.lang.SoftException(e);
}
}
}
</pre><p>except, in addition to wrapping the exception, it also affects
Java's static exception checking mechanism. </p><p> Like advice, the declare soft form has no effect in an
abstract aspect that is not extended by a concreate aspect. So
the following code will not compile unless it is compiled with an
extending concrete aspect:</p><pre class="programlisting">
abstract aspect A {
abstract pointcut softeningPC();
before() : softeningPC() {
Class.forName("FooClass"); // error: uncaught ClassNotFoundException
}
declare soft : ClassNotFoundException : call(* Class.*(..));
}
</pre></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="advice-precedence"></a>Advice Precedence</h3></div></div></div><p>
An aspect may declare a precedence relationship between concrete
aspects with the <code class="literal">declare precedence</code> form:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">declare precedence :
<em class="replaceable"><code>TypePatternList</code></em> ; </code></li></ul></div><p>This signifies that if any join point has advice from two
concrete aspects matched by some pattern in
<em class="replaceable"><code>TypePatternList</code></em>, then the precedence of
the advice will be the order of in the list. </p><p>In <em class="replaceable"><code>TypePatternList</code></em>, the wildcard "*" can
appear at most once, and it means "any type not matched by any other
pattern in the list". </p><p>For example, the constraints that (1) aspects that have
Security as part of their name should have precedence over all other
aspects, and (2) the Logging aspect (and any aspect that extends it)
should have precedence over all non-security aspects, can be
expressed by:</p><pre class="programlisting">
declare precedence: *..*Security*, Logging+, *;
</pre><p>
For another example, the CountEntry aspect might want to count the
entry to methods in the current package accepting a Type object as
its first argument. However, it should count all entries, even
those that the aspect DisallowNulls causes to throw exceptions.
This can be accomplished by stating that CountEntry has precedence
over DisallowNulls. This declaration could be in either aspect, or
in another, ordering aspect:
</p><pre class="programlisting">
aspect Ordering {
declare precedence: CountEntry, DisallowNulls;
}
aspect DisallowNulls {
pointcut allTypeMethods(Type obj): call(* *(..)) && args(obj, ..);
before(Type obj): allTypeMethods(obj) {
if (obj == null) throw new RuntimeException();
}
}
aspect CountEntry {
pointcut allTypeMethods(Type obj): call(* *(..)) && args(obj, ..);
static int count = 0;
before(): allTypeMethods(Type) {
count++;
}
}
</pre><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3092"></a>Various cycles</h4></div></div></div><p>
It is an error for any aspect to be matched by more than one
TypePattern in a single decare precedence, so:
</p><pre class="programlisting">
declare precedence: A, B, A ; // error
</pre><p>
However, multiple declare precedence forms may legally have this
kind of circularity. For example, each of these declare
precedence is perfectly legal:
</p><pre class="programlisting">
declare precedence: B, A;
declare precedence: A, B;
</pre><p>
And a system in which both constraints are active may also be
legal, so long as advice from A and B don't share a join
point. So this is an idiom that can be used to enforce that A and
B are strongly independent.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3099"></a>Applies to concrete aspects</h4></div></div></div><p>
Consider the following library aspects:
</p><pre class="programlisting">
abstract aspect Logging {
abstract pointcut logged();
before(): logged() {
System.err.println("thisJoinPoint: " + thisJoinPoint);
}
}
abstract aspect MyProfiling {
abstract pointcut profiled();
Object around(): profiled() {
long beforeTime = System.currentTimeMillis();
try {
return proceed();
} finally {
long afterTime = System.currentTimeMillis();
addToProfile(thisJoinPointStaticPart,
afterTime - beforeTime);
}
}
abstract void addToProfile(
org.aspectj.JoinPoint.StaticPart jp,
long elapsed);
}
</pre><p>
In order to use either aspect, they must be extended with
concrete aspects, say, MyLogging and MyProfiling. Because advice
only applies from concrete aspects, the declare precedence form
only matters when declaring precedence with concrete aspects. So
</p><pre class="programlisting">
declare precedence: Logging, Profiling;
</pre><p>
has no effect, but both
</p><pre class="programlisting">
declare precedence: MyLogging, MyProfiling;
declare precedence: Logging+, Profiling+;
</pre><p>
are meaningful.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="statically-determinable-pointcuts"></a>Statically determinable pointcuts</h3></div></div></div><p>Pointcuts that appear inside of <code class="literal">declare</code> forms
have certain restrictions. Like other pointcuts, these pick out join
points, but they do so in a way that is statically determinable. </p><p>Consequently, such pointcuts may not include, directly or
indirectly (through user-defined pointcut declarations) pointcuts that
discriminate based on dynamic (runtime) context. Therefore, such
pointcuts may not be defined in terms of</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">cflow</li><li class="listitem">cflowbelow</li><li class="listitem">this</li><li class="listitem">target</li><li class="listitem">args</li><li class="listitem">if</li></ul></div><p> all of which can discriminate on runtime information. </p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="semantics-aspects"></a>Aspects</h2></div></div></div><p>
An aspect is a crosscutting type defined by the <code class="literal">aspect</code>
declaration.
</p><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="aspect-declaration"></a>Aspect Declaration</h3></div></div></div><p>
The <code class="literal">aspect</code> declaration is similar to the
<code class="literal">class</code> declaration in that it defines a type and an
implementation for that type. It differs in a number of
ways:
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3130"></a>Aspect implementation can cut across other types</h4></div></div></div><p> In addition to normal Java class declarations such as
methods and fields, aspect declarations can include AspectJ
declarations such as advice, pointcuts, and inter-type
declarations. Thus, aspects contain implementation
declarations that can can cut across other types (including those defined by
other aspect declarations).
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3133"></a>Aspects are not directly instantiated</h4></div></div></div><p> Aspects are not directly instantiated with a new
expression, with cloning, or with serialization. Aspects may
have one constructor definition, but if so it must be of a
constructor taking no arguments and throwing no checked
exceptions.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3136"></a>Nested aspects must be <code class="literal">static</code></h4></div></div></div><p>
Aspects may be defined either at the package level, or as a static nested
aspect -- that is, a static member of a class, interface, or aspect. If it
is not at the package level, the aspect <span class="emphasis"><em>must</em></span> be
defined with the static keyword. Local and anonymous aspects are not
allowed.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="aspect-extension"></a>Aspect Extension</h3></div></div></div><p>
To support abstraction and composition of crosscutting concerns,
aspects can be extended in much the same way that classes can. Aspect
extension adds some new rules, though.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3144"></a>Aspects may extend classes and implement interfaces</h4></div></div></div><p>
An aspect, abstract or concrete, may extend a class and may implement
a set of interfaces. Extending a class does not provide the ability
to instantiate the aspect with a new expression: The aspect may still
only define a null constructor.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3147"></a>Classes may not extend aspects</h4></div></div></div><p>
It is an error for a class to extend or implement an aspect.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3150"></a>Aspects extending aspects
</h4></div></div></div><p>
Aspects may extend other aspects, in which case not only are fields
and methods inherited but so are pointcuts. However, aspects may only
extend abstract aspects. It is an error for a concrete aspect to
extend another concrete aspect.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="aspect-instantiation"></a>Aspect instantiation</h3></div></div></div><p>
Unlike class expressions, aspects are not instantiated with
<code class="literal">new</code> expressions. Rather, aspect instances are
automatically created to cut across programs. A program
can get a reference to an aspect instance using the static
method <code class="literal">aspectOf(..)</code>.
</p><p>
Because advice only runs in the context of an aspect instance, aspect
instantiation indirectly controls when advice runs.
</p><p>
The criteria used to determine how an aspect is instantiated
is inherited from its parent aspect. If the aspect has no parent
aspect, then by default the aspect is a singleton aspect.
How an aspect is instantiated controls the form of the
<code class="literal">aspectOf(..)</code> method defined on the
concrete aspect class.
</p><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3161"></a>Singleton Aspects</h4></div></div></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> { ... }</code></li><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> issingleton() { ... }</code></li></ul></div><p>
By default (or by using the modifier <code class="literal">issingleton()</code>)
an aspect has exactly one instance that cuts across the entire
program. That instance is available at any time during program
execution from the static method <code class="literal">aspectOf()</code>
automatically defined on all concrete aspects
-- so, in the above examples, <code class="literal">A.aspectOf()</code> will
return A's instance. This aspect instance is created as the aspect's
classfile is loaded.
</p><p>
Because the an instance of the aspect exists at all join points in
the running of a program (once its class is loaded), its advice will
have a chance to run at all such join points.
</p><p>
(In actuality, one instance of the aspect A is made for each version
of the aspect A, so there will be one instantiation for each time A
is loaded by a different classloader.)
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3176"></a>Per-object aspects</h4></div></div></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> perthis(<em class="replaceable"><code>Pointcut</code></em>) { ... }</code></li><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> pertarget(<em class="replaceable"><code>Pointcut</code></em>) { ... }</code></li></ul></div><p>
If an aspect A is defined
<code class="literal">perthis(<em class="replaceable"><code>Pointcut</code></em>)</code>, then
one object of type A is created for every object that is the
executing object (i.e., "this") at any of the join points picked out
by <em class="replaceable"><code>Pointcut</code></em>.
The advice defined in A will run only at a join point where the
currently executing object has been associated with an instance of
A.
</p><p> Similarly, if an aspect A is defined
<code class="literal">pertarget(<em class="replaceable"><code>Pointcut</code></em>)</code>,
then one object of type A is created for every object that is the
target object of the join points picked out by
<em class="replaceable"><code>Pointcut</code></em>.
The advice defined in A will run only at a join point where the
target object has been associated with an instance of
A.
</p><p>
In either case, the static method call
<code class="literal">A.aspectOf(Object)</code> can be used to get the aspect
instance (of type A) registered with the object. Each aspect
instance is created as early as possible, but not before reaching a
join point picked out by <em class="replaceable"><code>Pointcut</code></em> where
there is no associated aspect of type A.
</p><p> Both <code class="literal">perthis</code> and <code class="literal">pertarget</code>
aspects may be affected by code the AspectJ compiler controls, as
discussed in the <a class="xref" href="#implementation" title="Appendix C. Implementation Notes">Implementation Notes</a> appendix. </p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3202"></a>Per-control-flow aspects</h4></div></div></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> percflow(<em class="replaceable"><code>Pointcut</code></em>) { ... }</code></li><li class="listitem"><code class="literal">aspect <em class="replaceable"><code>Id</code></em> percflowbelow(<em class="replaceable"><code>Pointcut</code></em>) { ... }</code></li></ul></div><p>
If an aspect A is defined
<code class="literal">percflow(<em class="replaceable"><code>Pointcut</code></em>)</code> or
<code class="literal">percflowbelow(<em class="replaceable"><code>Pointcut</code></em>)</code>,
then one object of type A is created for each flow of control of the
join points picked out by <em class="replaceable"><code>Pointcut</code></em>, either
as the flow of control is entered, or below the flow of control,
respectively. The advice defined in A may run at any join point in
or under that control flow. During each such flow of control, the
static method <code class="literal">A.aspectOf()</code> will return an object
of type
A. An instance of the aspect is created upon entry into each such
control flow.
</p></div><div class="sect3"><div class="titlepage"><div><div><h4 class="title"><a name="idm3220"></a>Aspect instantiation and advice</h4></div></div></div><p>
All advice runs in the context of an aspect instance,
but it is possible to write a piece of advice with a pointcut
that picks out a join point that must occur before asopect
instantiation. For example:
</p><pre class="programlisting">
public class Client
{
public static void main(String[] args) {
Client c = new Client();
}
}
aspect Watchcall {
pointcut myConstructor(): execution(new(..));
before(): myConstructor() {
System.err.println("Entering Constructor");
}
}
</pre><p>
The before advice should run before the execution of all
constructors in the system. It must run in the context of an
instance of the Watchcall aspect. The only way to get such an
instance is to have Watchcall's default constructor execute. But
before that executes, we need to run the before advice...
</p><p>
There is no general way to detect these kinds of circularities at
compile time. If advice runs before its aspect is instantiated,
AspectJ will throw a <a class="ulink" href="../api/org/aspectj/lang/NoAspectBoundException.html" target="_top">
<code class="literal">org.aspectj.lang.NoAspectBoundException</code></a>.
</p></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="aspect-privilege"></a>Aspect privilege</h3></div></div></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><code class="literal">privileged aspect <em class="replaceable"><code>Id</code></em> { ... }</code></li></ul></div><p>
Code written in aspects is subject to the same access control rules as
Java code when referring to members of classes or aspects. So, for
example, code written in an aspect may not refer to members with
default (package-protected) visibility unless the aspect is defined in
the same package.
</p><p>
While these restrictions are suitable for many aspects, there may be
some aspects in which advice or inter-type members needs to access private
or protected resources of other types. To allow this, aspects may be
declared <code class="literal">privileged</code>. Code in priviliged aspects has
access to all members, even private ones.
</p><pre class="programlisting">
class C {
private int i = 0;
void incI(int x) { i = i+x; }
}
privileged aspect A {
static final int MAX = 1000;
before(int x, C c): call(void C.incI(int)) && target(c) && args(x) {
if (c.i+x > MAX) throw new RuntimeException();
}
}
</pre><p>
In this case, if A had not been declared privileged, the field reference
c.i would have resulted in an error signaled by the compiler.
</p><p>
If a privileged aspect can access multiple versions of a particular
member, then those that it could see if it were not privileged take
precedence. For example, in the code
</p><pre class="programlisting">
class C {
private int i = 0;
void foo() { }
}
privileged aspect A {
private int C.i = 999;
before(C c): call(void C.foo()) target(c) {
System.out.println(c.i);
}
}
</pre><p>
A's private inter-type field C.i, initially bound to 999, will be
referenced in the body of the advice in preference to C's privately
declared field, since the A would have access to its own inter-type
fields even if it were not privileged.
</p><p>
Note that a privileged aspect can access private inter-type
declarations made by other aspects, since they are simply
considered private members of that other aspect.
</p></div></div></div><div class="appendix"><div class="titlepage"><div><div><h1 class="title"><a name="implementation"></a>Appendix C. Implementation Notes</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="sect1"><a href="#idm3245">Compiler Notes</a></span></dt><dt><span class="sect1"><a href="#idm3275">Bytecode Notes</a></span></dt><dd><dl><dt><span class="sect2"><a href="#the-class-expression-and-string">The .class expression and String +</a></span></dt><dt><span class="sect2"><a href="#the-handler-join-point">The Handler join point</a></span></dt><dt><span class="sect2"><a href="#initializers-and-inter-type-constructors">Initializers and Inter-type Constructors</a></span></dt></dl></dd><dt><span class="sect1"><a href="#idm3322">Annotation-style Notes</a></span></dt><dt><span class="sect1"><a href="#idm3325">Summary of implementation requirements</a></span></dt></dl></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idm3245"></a>Compiler Notes</h2></div></div></div><p>
The initial implementations of AspectJ have all been
compiler-based implementations. Certain elements of AspectJ's
semantics are difficult to implement without making modifications
to the virtual machine, which a compiler-based implementation
cannot do. One way to deal with this problem would be to specify
only the behavior that is easiest to implement. We have chosen a
somewhat different approach, which is to specify an ideal language
semantics, as well as a clearly defined way in which
implementations are allowed to deviate from that semantics. This
makes it possible to develop conforming AspectJ implementations
today, while still making it clear what later, and presumably
better, implementations should do tomorrow.
</p><p>
According to the AspectJ language semantics, the declaration
</p><pre class="programlisting">
before(): get(int Point.x) { System.out.println("got x"); }
</pre><p>
should advise all accesses of a field of type int and name x from
instances of type (or subtype of) Point. It should do this
regardless of whether all the source code performing the access
was available at the time the aspect containing this advice was
compiled, whether changes were made later, etc.
</p><p>
But AspectJ implementations are permitted to deviate from this in
a well-defined way -- they are permitted to advise only accesses
in <span class="emphasis"><em>code the implementation controls</em></span>. Each
implementation is free within certain bounds to provide its own
definition of what it means to control code.
</p><p>
In the current AspectJ compiler, ajc, control of the code means
having bytecode for any aspects and all the code they should
affect available during the compile. This means that if some class
Client contains code with the expression <code class="literal">new
Point().x</code> (which results in a field get join point at
runtime), the current AspectJ compiler will fail to advise that
access unless Client.java or Client.class is compiled as well. It
also means that join points associated with code in native methods
(including their execution join points) cannot be advised.
</p><p>
Different join points have different requirements. Method and
constructor call join points can be advised only if ajc controls
the bytecode for the caller. Field reference or assignment join
points can be advised only if ajc controls the bytecode for the
"caller", the code actually making the reference or assignment.
Initialization join points can be advised only if ajc controls the
bytecode of the type being initialized, and execution join points
can be advised only if ajc controls the bytecode for the method or
constructor body in question.
The end of an exception handler is underdetermined in bytecode,
so ajc will not implement after or around advice on handler join
points.
Similarly, ajc cannot implement around advice on initialization
or preinitialization join points.
In cases where ajc cannot implement advice, it will emit a
compile-time error noting this as a compiler limitation.
</p><p>
Aspects that are defined <code class="literal">perthis</code> or
<code class="literal">pertarget</code> also have restrictions based on
control of the code. In particular, at a join point where the
bytecode for the currently executing object is not available, an
aspect defined <code class="literal">perthis</code> of that join point will
not be associated. So aspects defined
<code class="literal">perthis(Object)</code> will not create aspect
instances for every object unless <code class="literal">Object</code>is part
of the compile. Similar restrictions apply to
<code class="literal">pertarget</code> aspects.
</p><p>
Inter-type declarations such as <code class="literal">declare parents</code>
also have restrictions based on control of the code. If the
bytecode for the target of an inter-type declaration is not
available, then the inter-type declaration is not made on that
target. So, <code class="literal">declare parents : String implements
MyInterface</code> will not work for
<code class="literal">java.lang.String</code> unless
<code class="literal">java.lang.String</code> is part of the compile.
</p><p>
When declaring members on interfaces, the implementation must
control both the interface and the top-level implementors of
that interface (the classes that implement the interface but
do not have a superclass that implements the interface).
You may weave these separately, but be aware that you will get
runtime exceptions if you run the affected top-level classes
without the interface as produced by the same ajc implementation.
Any intertype declaration of an abstract method on an interface
must be specified as public, you will get a compile time error
message indicating this is a compiler limitation if you do not
specify public. A non-abstract method declared on an interface
can use any access modifier except protected. Note that this is
different to normal Java rules where all members declared in
an interface are implicitly public.
Finally, note that one cannot define static fields or methods
on interfaces.
</p><p>
When declaring methods on target types, only methods declared
public are recognizable in the bytecode, so methods must be
declared public to be overridden in any subtype or to be called
from code in a later compile using the target type as a library.
</p><p>
Other AspectJ implementations, indeed, future versions of ajc, may
define <span class="emphasis"><em>code the implementation controls</em></span> more
liberally or restrictively, so long as they comport with the Java
language. For example, the <code class="literal">call</code> pointcut does
not pick out reflective calls to a method implemented in
<code class="literal">java.lang.reflect.Method.invoke(Object, Object[])</code>.
Some suggest that the call "happens" and the call pointcut should
pick it out, but the AspectJ language shouldn't anticipate what happens
in code outside the control of the implementation, even when it
is a a well-defined API in a Java standard library.
</p><p>
The important thing to remember is that core concepts of AspectJ,
such as the join point, are unchanged, regardless of which
implementation is used. During your development, you will have to
be aware of the limitations of the ajc compiler you're using, but
these limitations should not drive the design of your aspects.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idm3275"></a>Bytecode Notes</h2></div></div></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="the-class-expression-and-string"></a>The .class expression and String +</h3></div></div></div><p> The java language form <code class="literal">Foo.class</code> is
implemented in bytecode with a call to
<code class="literal">Class.forName</code> guarded by an exception
handler catching a <code class="literal">ClassNotFoundException</code>.
</p><p> The java language + operator, when applied to String
arguments, is implemented in bytecode by calls to
<code class="literal">StringBuffer.append</code>.
</p><p> In both of these cases, the current AspectJ compiler
operates on the bytecode implementation of these language
features; in short, it operates on what is really happening rather
than what was written in source code. This means that there may
be call join points to <code class="literal">Class.forName</code> or
<code class="literal">StringBuffer.append</code> from programs that do not,
at first glance, appear to contain such calls:
</p><pre class="programlisting">
class Test {
void main(String[] args) {
System.out.println(Test.class); // calls Class.forName
System.out.println(args[0] + args[1]); // calls StringBuffer.append
}
}
</pre><p>In short, the join point model of the current AspectJ
compiler considers these as valid join points.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="the-handler-join-point"></a>The Handler join point</h3></div></div></div><p>The end of exception handlers cannot reliably be found in Java
bytecode. Instead of removing the handler join point entirely, the
current AspectJ compiler restricts what can be done with the handler
join point:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">After and around advice cannot apply to handler
join points.</li><li class="listitem">The control flow of a handler join point cannot be
detected. </li></ul></div><p>
The first of these is relatively straightforward. If any piece of
after advice (returning, throwing, or "finally") would normally
apply to a handler join point, it will not in code output by the
current AspectJ compiler. A compiler warning is generated whenever
this is detected to be the case. Before advice is allowed.
</p><p> The second is that the control flow of a handler join point
is not picked out. For example, the following pointcut
</p><pre class="programlisting">
cflow(call(void foo()) || handler(java.io.IOException))
</pre><p> will capture all join points in the control flow of a call to
<code class="literal">void foo()</code>, but it will <span class="emphasis"><em>not</em></span>
capture those in the control flow of an
<code class="literal">IOException</code> handler. It is equivalent to
<code class="literal">cflow(call(void foo()))</code>. In general,
<code class="literal">cflow(handler(<em class="replaceable"><code>Type</code></em>))</code>
will not pick out any join points, the one exception to this is join points
that occur during the execution of any before advice on the handler.
</p><p> This does not restrict programs from placing before advice on
handlers inside <span class="emphasis"><em>other</em></span> control flows. This
advice, for example, is perfectly fine:
</p><pre class="programlisting">
before(): handler(java.io.IOException) && cflow(void parse()) {
System.out.println("about to handle an exception while parsing");
}
</pre><p>
A source-code implementation of AspectJ (such as AspectJ 1.0.6) is
able to detect the endpoint of a handler join point, and as such
will likely have fewer such restrictions.
</p></div><div class="sect2"><div class="titlepage"><div><div><h3 class="title"><a name="initializers-and-inter-type-constructors"></a>Initializers and Inter-type Constructors</h3></div></div></div><p>
The code for Java initializers, such as the assignment to the
field d in
</p><pre class="programlisting">
class C {
double d = Math.sqrt(2);
}
</pre><p>
are considered part of constructors by the time AspectJ gets ahold
of bytecode. That is, the assignment of d to the square root of
two happens <span class="emphasis"><em>inside</em></span> the default constructor of
C.
</p><p>
Thus inter-type constructors will not necessarily run a target
type's initialization code. In particular, if the inter-type
constructor calls a super-constructor (as opposed to a
<code class="literal">this</code> constructor), the target type's
initialization code will <span class="emphasis"><em>not</em></span> be run when that
inter-type constructor is called.
</p><pre class="programlisting">
aspect A {
C.new(Object o) {} // implicitly calls super()
public static void main(String[] args) {
System.out.println((new C() ).d); // prints 1.414...
System.out.println((new C(null)).d); // prints 0.0
}
</pre><p>
It is the job of an inter-type constructor to do all the required
initialization, or to delegate to a <code class="literal">this</code>
constructor if necessary.
</p></div></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idm3322"></a>Annotation-style Notes</h2></div></div></div><p>Writing aspects in annotation-style is subject to the same
bytecode limitations since the binary aspects take the same
form and are woven in the same way. However, the implementation
differences (e.g., the mechanism for implementing around advice)
may be apparent at runtime. See the documentation on annotation-style
for more information.
</p></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idm3325"></a>Summary of implementation requirements</h2></div></div></div><p>
This summarizes the requirements of our implementation of AspectJ.
For more details, see the relevant sections of this guide.
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem"><p>The invoking code must be under the control of ajc
for the following join points:</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: circle; "><li class="listitem">call join point</li><li class="listitem">get join point</li><li class="listitem">set join point</li></ul></div></li><li class="listitem"><p>The declaring/target code must be under the control of ajc
for the following join points and inter-type declarations:</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: circle; "><li class="listitem">execution join point</li><li class="listitem">adviceexecution join point</li><li class="listitem">handler join point</li><li class="listitem">initialization join point</li><li class="listitem">preinitialiaztion join point</li><li class="listitem">staticinitialization join point</li><li class="listitem">perthis aspect</li><li class="listitem">pertarget aspect</li><li class="listitem">declare parents</li><li class="listitem">declare method or field (see interface caveats below)</li></ul></div></li><li class="listitem"><p>Implementation Caveats</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: circle; "><li class="listitem"><p>The initialization and preinitialization join points
do not support around advice</p></li><li class="listitem"><p>The handler join point does not support...</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: square; "><li class="listitem">after advice</li><li class="listitem">around advice</li><li class="listitem">cflow(handler(..))</li></ul></div></li><li class="listitem"><p>Declaring members on an interface in an aspect affects only
the topmost implementing classes the implementation controls.</p></li><li class="listitem"><p>cflow and cflowbelow pointcuts work within a single thread.</p></li><li class="listitem"><p>
Runtime <code class="literal">ClassCastException</code> may result
from supplying a supertype of the actual type as an argument
to proceed(..) in around advice.</p></li></ul></div></li></ul></div></div></div></div></body></html>
|