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

Simple.java 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import org.aspectj.testing.Tester;
  2. import org.aspectj.lang.NoAspectBoundException;
  3. public class Simple {
  4. public static void main(String[] args) {
  5. C c = new C();
  6. c.m();
  7. // aspect A is bound to the base class C
  8. Tester.checkEqual(c.history.toString(), "A.before, C.m, ", "C");
  9. SubC1 subc1 = new SubC1();
  10. subc1.m();
  11. // aspect A is also bound to the subclass SubC1
  12. Tester.checkEqual(subc1.history.toString(), "A.before, SubC1.m, C.m, ", "SubC1");
  13. SubC2 subc2 = new SubC2();
  14. subc2.m();
  15. // aspect A is overriden by SubA on the class SubC2
  16. Tester.checkEqual(subc2.history.toString(), "SubA2.before, A.before, A.before, C.m, ", "SubC2");
  17. Tester.check(SubA1.aspectOf(subc2) instanceof SubA1, "SubA1.aspectOf(subc2) instanceof SubA1");
  18. // retrieving the SubA aspect using its own aspectOf method
  19. Tester.check(SubA2.aspectOf(subc2) instanceof SubA2, "Sub2A.aspectOf(subc2) instanceof SubA2");
  20. try {
  21. // trying to retrieve a SubA aspect where only an A aspect is present
  22. SubA2 subA = SubA2.aspectOf(c);
  23. Tester.checkFailed("SubA2.aspectOf(c) should throw an exception");
  24. } catch (NoAspectBoundException nae) {
  25. Tester.note("NoAspectException caught");
  26. }
  27. Tester.check("NoAspectException caught");
  28. }
  29. }
  30. class C {
  31. // records what methods are called and advice are run
  32. public StringBuffer history = new StringBuffer();
  33. public void m() {
  34. history.append("C.m, ");
  35. }
  36. }
  37. class SubC1 extends C {
  38. public void m() {
  39. history.append("SubC1.m, ");
  40. super.m();
  41. }
  42. }
  43. class SubC2 extends C {
  44. }
  45. abstract aspect A pertarget(targets()) {
  46. abstract pointcut targets();
  47. StringBuffer history = null;
  48. after (C c) returning (): target(c) && initialization(new(..)) {
  49. //System.out.println(thisJoinPoint);
  50. history = c.history;
  51. }
  52. before (): call(void m()) {
  53. history.append("A.before, ");
  54. }
  55. }
  56. aspect SubA1 extends A {
  57. pointcut targets(): target(C);
  58. }
  59. aspect SubA2 extends A {
  60. pointcut targets(): target(SubC2);
  61. before (): call(void m()) {
  62. history.append("SubA2.before, ");
  63. }
  64. }