Yaron Israeli
Yaron Israeli

Reputation: 351

Determine local variable name in AspectJ

I'm new with AspectJ and I try to do this:

Lets say I have 2 objects: var_obj1, var_obj2.

They are of the same type: MyObject.

In my aspect, I'm using an around() advice on the toString() method on MyObject. I want to return the object variable name

For example, if I call toString() on var_obj1, this method (on the aspect) should return: "hello from var_obj1".

and if I call toString() on var_obj2, this method (on the aspect) should return: "hello from var_obj2".

This should be done without saving the variable name in the object.

I'm searching for an AspectJ solution for this.

My current code:

public static void main(String[] args) {
  MyObject var_obj1, var_obj2;
  var_obj1 = new MyObject();
  var_obj2 = new MyObject();

  System.out.println(var_obj1.toString());
  System.out.println(var_obj2.toString());
}

Aspect:

String around(): execution(String com.example.shapes.MyObject.toString()) {
  var object_var_name = ""; // here we need to put the variable object name
  return "hello from "+object_var_name;
}

Upvotes: 0

Views: 245

Answers (1)

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7098

What you want to achieve is not possible with AspectJ. First of all, because there's no pointcut expression to pick out join-points where the method execution (or rather method-call) is based on accessing a local variable. Besides that, you shouldn't build your application logic based on the naming or even the use of local variables, a method could be invoked without using a local variable at all. Consider the following examples:

new MyObject().toString();
someOtherObject.getMyObject().toString();

Both perfectly valid invocations of toString(), yet no local variables were used.

Upvotes: 1

Related Questions