Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the method name at compile time?

How do I get the enclosing method name at compile time?

And why has it been difficult for me to figure this out? Why wouldn't Java want me to do this? I don't see any inherent problems with a feature like this, and it's useful for logging method names without duplication between the method signature and the string constant like so:

private void methodName() {
   final String MN = "methodName";
   ...

Someone might change the method name without changing the MN constant, and then I can't find it in the log.

I know Java has a (reflective?) method for doing this, but why anyone would want to over-complicate things and create the possibility of errors with a run-time solution (for this particular problem) is beyond me.

Apparently macros are bad practice, but I think this is a pretty good use case for them. That's what I'm basically going for, something like a macro, a constant.

Btw, this question is pretty similar:

Getting the name of the current executing method

None of the solutions are constants derived at compile time, though. They're all run-time computations.


EDIT: Why can't it be done at compile time?

Please don't give a trivial answer like "that's the way Java was designed", because then I'll just ask "why ?"

like image 997
Mike Avatar asked Feb 16 '15 23:02

Mike


People also ask

How do you get a method name?

Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.


1 Answers

From the answer https://stackoverflow.com/a/5891326/4353712:

String name = new Object(){}.getClass().getEnclosingMethod().getName();

However, as mentioned in the answer, this generates a new .class file every time you use it.

like image 69
Sándor Mátyás Márton Avatar answered Oct 17 '22 01:10

Sándor Mátyás Márton