0

I know that I can retrieve the arguments sent to a method, but how could I get objects defined in that method? For example, this is my class:

    public class Sample {
        public static void sendMessage(String message) {
            String x = "string x";
            System.out.println(message);
        }

        public static void main(String[] args) {
            sendMessage("my message");
        }
    }

And this is my aspect:

public aspect SampleAspect {
    pointcut printMessage(String m) : call(void Sample.sendMessage(..)) && args(m);
    before(String m) : printMessage(m) {
        System.out.println("Before sending: " + m);
    }
    after(String m) : printMessage(m) {
        System.out.println("After sending: " + m);
    }
}

The outputs consist of the argument, because I wrote && args(m). How could I get the another string, x, from sendMessage?

Sorin
  • 908
  • 2
  • 8
  • 19

1 Answers1

3

There is no way to access local variables from a method that is being advised by an aspect. This is because local variables are not exposed via any joinpoints.

If you need to access local variables, then you will have to refactor the target code so that they are exposed. You can do something like this:

public class Sample {
    public static void sendMessage(String message) {
        String x = getX();
        System.out.println(message);
    }
    public static String getX() {
        return "string x";
    }

    public static void main(String[] args) {
        sendMessage("my message");
    }
}

Then, you can advise the call of the method getX. If you need to access both message and x, this is still possible, but you would need to use a wormhole pattern to do so. I can explain if this is what you need.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
  • Thanks! Say I have a stack and I have to print to console all the elements from it using AspectJ. Every time I pop an element, I send it to an empty method, like this: doNothing(stack.pop()), where doNothing(..) has an empty body {}. I do this because I want to access the elements from an aspect. Is there a better way? – Sorin Jun 12 '13 at 08:33
  • Why don't you advise calls to stack.pop()? Something like this: before(Stack s) : call(* Stack.pop()) && target(s) && withinCode() – Andrew Eisenberg Jun 12 '13 at 15:44
  • This sounds better! Thank you again! – Sorin Jun 12 '13 at 16:21