views:

169

answers:

2

Hi,

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  A: 

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

KLE
Concerning the first solution, I can't do it, since I don't throw the exception. I think my first solution was quite dumb, since I made the mistake of confusing throwing and catching, even if i catch my own exception that doesn't mean that was the one thrown..
LB
+1  A: 

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.

Aaron Digulla
but if i've many many classes, the map is going to be huge. I would have to dramatically change the framework. tough...
LB
So i've found that calling getMethods and iterating over the array seems to be quicker. Thanks for the help. I was able to wrap the call to getMethod this way.
LB