Reputation: 198198
For example, I have a class with a public field and corresponding getter/setters:
public class User {
public String name;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
}
Now invoke the field name
:
User user = new User();
user.name = "test";
System.out.println(user.name);
Is it able to use aspectj to enhance the class to let the bytecode be:
User user = new User();
user.setName("test");
System.out.println(user.getName());
I know javassist can do this, but can AspectJ do the same?
Upvotes: 1
Views: 2840
Reputation: 91
User user = new User();
user.setName("Bob"); //<- This line matched the pointcut below
user.name = "Alex"; //<- This line too matched the pointcut below
System.out.println("User name is " + user.name);
For the above code in the main method of User class, I wrote the below Aspect
public aspect UserAspect {
public pointcut propSet() : set(* User.*);
void around() : propSet(){
System.out.println(thisJoinPoint.getSignature() + " is being set");
proceed();
}
}
And the output was..
String test.User.name is being set
String test.User.name is being set
User name is Bob
So, my understanding is that AspectJ treats member variable assignment and a setter the same way. So, it might not be possible what you were able to do with Javassist
Upvotes: 2
Reputation: 160181
Check out the pointcut docs and theget(FieldPattern)
and set(FieldPattern)
pointcuts.
There is some additional writeup in the same doc.
Upvotes: 2