Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
11 July 2006 @ 1am

Tagged
Java, Ruby, Software

Discuss

Evil magic: Getting the name of a method within the method in Ruby (or Java?)

During my dark days of java, I often wanted to be able to reflectively get the name of the method called inside the method in order to log things, inspect things, etc. It was always impossible, at least as far as I knew back then - though in light of new knowledge, I wonder if you couldn't throw an exception, then catch it and inspect the stack trace?

Anyways, saw on ruby-lang this little trick to do it in ruby:

RUBY:
  1. def method_called
  2.  caller[0].match(/`([^']+)/).captures[0]
  3. end
  4. def test_me
  5. p method_called
  6. end
  7. test_me
  8. #=> "test_me"

Its a bit hacky and evil, and I'm sure its not fast, but it works.


2 Comments

Posted by
Ben Pryor
11 July 2006 @ 7am

Java logging frameworks that I’ve looked at (log4j being the most popular) get method names by creating an exception and inspecting the stack trace like you said. It’s not fast, and that’s why it’s not recommended to log method names in production. You don’t have to actually throw and then catch the exception: new Exception().getStackTrace() is good enough.

A faster way (in Java) is to use AOP / bytecode manipulation as a post-compile step to insert logging statements at method entry and exit.


Posted by
Rob
11 July 2006 @ 8am

Thanks for the details, Ben. I knew that you could do it with AOP/bytecode stuff, though I prefer when something like this can be built into/added on to the language in plain code instead of additional libraries.


Leave a Comment

Living with Half a Brain What I Want From TextMate…