简体   繁体   中英

AspectJ vs. toString()


public pointcut myToString() : within(mypackage.*) 
&& execution(public String toString());

String around(): myToString(){
    System.out.println("myToString");
    return proceed();
}

It works only if I override toString in class Im trying to weave, is there any way to make it work on all toString methods?

It won't work because within() only matches execution within your package, but you're inheriting the toString() method unless you it is declared explicitly.

Edit: I had a look, cflow won't work either. I can't see another way to do this without load-time weaving, but this would entail logging all calls to toString() which is a very bad idea. You're probably much better off simply declaring toString() in all your methods with return super.toString() so your original pointcut will work (and if toString() is never called otherwise you don't lose anything).

If you are determined to pursue this approach, there's a section of the aspectj documentation that will get you started with load-time weaving.

Update: One other option is to use Eclipse's Detail Formatters . They allow you to decorate the toString() methods for debugging purposes.


Original answer: You could try using cflow to match any join point in the control flow of toString(). Note I've not been able to verify this, so check the syntax (it might also need to be execution() rather than call(), though I can't recall for sure). For example:

public pointcut myToString() : cflow(call(String mypackage.*.toString()));

One other point, beware of adding System.out calls, consider using a logging framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM