• Post Reply Bookmark Topic Watch Topic
  • New Topic

Retrieving a method's name from within that very method  RSS feed

 
Julien Martin
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Suppose I have a method as follows:

How can I dynamically retrieve the method's name, ie "myMethod" using java reflection?? What do I need to insert HERE in order to retrieve the method's name and thus avoid it from being hard-coded?

Thanks in advance,

Julien.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at java.lang.Throwable and the getStackTrace method JavaDocs. The StackTraceElement[] can be used to get the entire calling sequence that resulted in your method being called.

Bill
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an advanced question. Moving...
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can get the reference of the class using

Class c = this.getClass();
Methods [] m = c.getMethods();

Now after you have the class , you can investigate the methods in that class in runtime.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Rahul, but that won't tell Julien the name of the method that's currently executing.
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh! sorry for misunderstanding the question.

In this case William Brogden's suggested solution should work.
You can throw an exception and catch that and inspect.
 
Julien Martin
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks a lot. Taking into account the performance overhead and the extra code necessary to put in place my logging methods I decided to go for something simpler as follows:



I then use the public logger variable as follows:



Thus I can use my own logging configuration with a logging file and there is no need for retrieving the method's name dynamically.

Julien.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!