• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting the current method that this executing.  RSS feed

 
Zak Nixon
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have about 40 methods that need to
be overwritten and throwing an UnsupportedOperationException(...).

I want to say the following




The result would print out :
Can't do sampleClass.

Any suggestions would be nice.

Thanks

Zak
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since JDK 1.4, the Throwable class has the "getStackTrace()" method, which returns an array of StackTraceElement objects, which can tell you the name of the method.

String methodName = new Throwable().getStackTrace[0].getMethodName();

In real code, I wouldn't chain all this together: getStackTrace() can return a 0-length array. You'd have to check for that.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Note that Ernest forgot the () after getStackTrace. To make it safe against getStackTrace() returning an empty array, you'd write it like this:

[ July 25, 2006: Message edited by: Jesper Young ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The above posts do give good guidance about how to get the current method name. However, I am a bit doubtful why you want to do that, in your particular example.

Do the exception messages really need to contain the method name? The exception stack traces will make the method name clear anyway. Perhaps you are logging exception messages, but not logging stack traces?

If you do need the method name in the message, I would have thought it would be quicker for you, faster to execute, easier to maintain just to "bite the bullet" and type in those 40 method names. If you want to be really flash, a smart editor could probably be programmed to do it automatically (I reckon I could get emacs to do it).

In general, always favour simple obvious code over clever code. As a rule, if someone says your code is "clever", it's an insult, not a compliment!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!