Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get method parameter values using AspectJ

I am using AspectJ to capture method calls. Then I need to get the method name and the parameter values passed. Let's have the following example:

Line2D line = new Line2D.Double(lineStart, lineEnd);
and graphics.draw(line);

I need to capture all calls to Graphics2D.draw(Shape). I have a pointcut that does this:

pointcut captureCallParameters(Shape name) : call(* *(Shape)) && args(name);

The problem is when I try to get the value of the parameter (Shape in this method). I get this parameter: java.awt.geom.Line2D$Double@596e1fb1

Instad I want to get the points for the shape which is a line in this case.

On the other hand I have also a pointcut that matches the construction of the new line mentioned above and I am able to get the parameters of that line. BUT I don't know how to relate the Draw method with that line constructor. I can have several constructors for Lines and I don't know which one of those Lines is drawn using the Draw(line) method.

like image 236
Gonny Avatar asked Nov 21 '11 08:11

Gonny


1 Answers

You have it completely right!

You have indeed caught the Line2D instance that you were looking for. However, you seem to be printing out the shape variable in the System.out.println(shape) statement. What you have there java.awt.geom.Line2D$Double@596e1fb1 is the identifier of the variable. You can now access the contents of the variable by calling any available method (for example shape.getBounds()).

Furthermore, you can do the following:

Line2D line = (Line2D) shape; // cast it to Line2D
line.getX1(); // will give you X1 of your line
line.getX2(); // will give you X2 of your line

One last point, here is a better pointcut definition for your use case:

pointcut captureCallParameters(Shape shape) : call(* Graphics2D.draw(..)) && args(shape);

In your pointcut, you will intercept all the method calls that have the Shape argument. In my version, you will only capture the invocation of the draw() method.

like image 162
Guven Avatar answered Oct 05 '22 02:10

Guven