如果我使用反射并且想查找某个方法是否已实现,我可以使用 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
发布评论
评论(2)
我确认您的绩效衡量标准。
我在一本java性能书中读到了一个解决方案。我们已将其应用到我们自己的应用程序中,以应对一些例外情况(其中堆栈跟踪并不重要,并且可能的频率很高)。我不知道你是否会喜欢它......;-)
创建 Exception 类的唯一实例,并将其存储。抛出该实例。
当您不想干扰依赖异常的现有流程时,这似乎是理想的选择。
如果您的编译器抱怨其他方法没有抛出该异常,那是因为您选择了已检查的异常。
使用 RuntimeException 的子类(它们是未经检查的,因此编译器不知道它们是否被抛出,他不会抱怨)。
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).
不可以,因为
getMethod()
直接调用new
,并且您无法替换NoSuchMethodException
的代码,因为该类已签名且fillInStackTrace ()
是本机
。最好的选择是将
getMethod()
的调用缓存在一个中心位置:只需创建一个两级映射:Map>
和使用快速查找而不抛出任何异常。No, since
getMethod()
callsnew
directly and you can't replace the code forNoSuchMethodException
since the class is signed andfillInStackTrace()
isnative
.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.