Java:获取当前正在执行的Method对应的对象 [英] Java : Getting the currently executing Method corresponding object

查看:111
本文介绍了Java:获取当前正在执行的Method对应的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取当前正在执行的方法作为 Method 对象的最优雅的方法是什么?

What is the most elegant way to get the currently executing method as a Method object ?

我第一个明显的方法是在辅助类中使用静态方法,该方法将加载当前线程堆栈,获取正确的堆栈跟踪元素,并根据其信息构造 Method 元素.

My first obvious way to do it would be to use a static method in a helper class, which would load the current thread stack, get the right stack trace element, and construct the Method element from its information.

有没有更优雅的方法来实现这一目标?

Is there a more elegant way to achieve this?

推荐答案

开箱即用,我不知道有更好的方法来做到这一点.

Out of the box, I'm not aware of a better way to do this.

可能需要考虑的一件事是方面 - 您可以将方面编织到围绕所有方法调用触发的代码中,并将当前 Method 对象推送到 ThreadLocal(基于从连接点).

One thing to consider perhaps would be aspects - you could weave an aspect into the code that fired around all method invocations and pushed the current Method object to a ThreadLocal (based on the reflective information available from the joinpoint).

如果它真的在所有方法上触发,这可能会非常昂贵,但是根据您对结果的处理方式,您可以将捕获限制为某些包/类,这会有所帮助.您也可以将 Method 的实际查找推迟到它被使用的时候,而是存储方法的名称和参数等.

This would be probably prohibitively expensive if it really fired on all methods, but depending on what you're doing with the results, you may be able to constrain the capturing down to certain packages/classes, which would help. You may be able to defer the actual lookup of the Method too until such time as it's used, and instead store the name of the method and arguments etc.

我怀疑是否会有一种特别便宜的方法来实现这一目标.

I have my doubts whether there's going to be a particularly cheap way to achieve this, though.

这篇关于Java:获取当前正在执行的Method对应的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆