重写标准 JVM 异常的 fillInStackTrace

发布于 2024-08-07 05:08:15 字数 373 浏览 4 评论 0 原文

如果我使用反射并且想查找某个方法是否已实现,我可以使用 getMethod() 方法。此方法抛出 NoSuchMethodException。

有没有办法重载此异常的 fillInStackTrace 以优化性能?目前,大约 40% 的时间都花在这个方法上。

我正在使用一个框架,该框架使用异常作为执行某种控制流的方式。

所以我不想太具有侵略性。如果我创建一个扩展 Throwable 的类并使用这个新类而不是 NoSuchMethodException,我会得到类似的结果:

NewException is never thrown in body of corresponding trystatement

谢谢

If I'm using reflection and I want to find if a method is implemented or not, i can use the getMethod() method. This method throws a NoSuchMethodException.

Is there a way to overload the fillInStackTrace of this Exception to optimize the performance ? Right now, about 40% of the time is spent in this Method.

I'm using a framework using exceptions as a way to perform a certain kind of control flow.

So I don't want to be too invasive. If i'm creating a class extending Throwable and using this new class instead of NoSuchMethodException, I'm having something like:

NewException is never thrown in body of corresponding trystatement

thanks

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

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

发布评论

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

评论(2

浅笑依然 2024-08-14 05:08:15

我的以下两点并不能完全解决您的问题标题,但我认为它们可能会有所帮助......


我确认您的绩效衡量标准。

我在一本java性能书中读到了一个解决方案。我们已将其应用到我们自己的应用程序中,以应对一些例外情况(其中堆栈跟踪并不重要,并且可能的频率很高)。我不知道你是否会喜欢它......;-)

创建 Exception 类的唯一实例,并将其存储。抛出该实例

当您不想干扰依赖异常的现有流程时,这似乎是理想的选择。


如果您的编译器抱怨其他方法没有抛出该异常,那是因为您选择了已检查的异常。
使用 RuntimeException 的子类(它们是未经检查的,因此编译器不知道它们是否被抛出,他不会抱怨)。

My two following points don't exactly solution the title of your question, but I think they could be helpful...


I confirm your performance measure.

I read about a solution in a java performance book. We have applied this to our own application, for some exceptions (where the stack trace is not important, and the possible frequency is high). I don't know if you will like it ... ;-)

Create a unique instance of your Exception class, store it. Throw that instance.

This seems ideal when you don't want to disturb an existing flow that relies on exceptions.


If your compiler complains about the other method not throwing that exception, it is because you chose a checked Exception.
Use a subclass of RuntimeException (they are unchecked, so the compiler doesn't know if they are thrown or not, he won't complain).

太阳男子 2024-08-14 05:08:15

不可以,因为 getMethod() 直接调用 new,并且您无法替换 NoSuchMethodException 的代码,因为该类已签名且 fillInStackTrace ()本机

最好的选择是将 getMethod() 的调用缓存在一个中心位置:只需创建一个两级映射:Map> 和使用快速查找而不抛出任何异常。

No, since getMethod() calls new directly and you can't replace the code for NoSuchMethodException since the class is signed and fillInStackTrace() is native.

Your best bet is to cache calls to getMethod() in a central place: Just create a two level map: Map<Class, Map<String, Method>> and use a quick lookup without any exception throwing.

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