AspectJ 与 toString()

发布于 2024-07-27 20:29:03 字数 287 浏览 2 评论 0原文


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

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

仅当我在尝试编织的类中重写 toString 时,它才有效,有什么方法可以使其在所有 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情泪▽动烟 2024-08-03 20:29:03

它不起作用,因为 inside() 只匹配包内的执行,但除非显式声明,否则您将继承 toString() 方法。

编辑:我看了一下,cflow 也不起作用。 我看不到没有加载时编织的另一种方法来做到这一点,但这将需要记录所有对 toString() 的调用,这是一个非常糟糕的主意。
您可能最好在所有方法中简单地声明 toString() 并返回 super.toString() ,这样您的原始切入点就可以工作(如果 toString() 从未被调用,否则您就不会失去任何东西)。

如果您决定采用这种方法,请参阅 aspectj 文档的一部分 这将帮助您开始加载时编织。

更新:另一种选择是使用 Eclipse 的 详细信息格式化程序。 它们允许您装饰 toString() 方法以进行调试。


原答案:
您可以尝试使用cflow来匹配toString()控制流中的任何连接点。 请注意,我无法验证这一点,因此请检查语法(它可能还需要是execution() 而不是call(),尽管我无法确定)。
例如:

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

另一点,注意添加 System.out 调用,考虑使用日志框架。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文