I want to access a local variable from a method in a business class, in a method which is in an aspect class. For instance
class BusinessClass {
public void simpleTest() {
...
String localString = new String( "test" );
...
}
}
MyAspect {
log() {
// I WANT TO ACCESS THE VALUE OF LOCALSTRING HERE
}
}
I want to access localString's value in log method of MyAspect. Please let me know if there is any way to accomplish this using Spring / AspectJ. Also, is there is a way to accomplish without changing simpleTest method signature?
Thanks much in advance!
Unfortunately, local variables are not exposed via joinpoints. This means that you cannot write a pointcut to match them. So, the answer is no, you cannot do this directly.
However, if you were to refactor your code so that the local variable were created inside of a method, then you could access it.
Conceptually, this kind of refactoring might be better for you code. Rather than simply allocate a new local variable, you can be explicit about what the allocation is doing by encapsulating it in a well-named method.
For example, this:
String localString = new String( "test" );
becomes this:
String localString = allocateTestString(); // or some better name
With this method:
private String allocateTestString() {
return new String( "test" )
}
Then you can write a pointcut to capture the local variable this way:
after() returning(String var) : call(private String allocateTestString()) {
// do something fun
}