Overriding fillInStackTrace for a standard JVM Exceptions

夙愿已清 提交于 2019-12-23 04:02:06

问题


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


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/1520859/overriding-fillinstacktrace-for-a-standard-jvm-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!