Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top