Also: getting the name of enclosing class. Useful, for log definition.

Based on https://stackoverflow.com/questions/442747/getting-the-name-of-the-currently-executing-method

https://stackoverflow.com/questions/5733427/why-isnt-getclass-available-as-a-static-method/9221495

To get current class you can use this idiom:

Complete example:

Will print true

That is cl points to Bar.class that. cl is local variable inside method that is defined in the class Bar.

It can be useful for example, if you want to define log:

Now, you can copy&paste log definition above (lines 5–6 and imports) to any class when you want to use log. This definition will have the same effect as:

with the main advantage that you don’t need to change the log definition (class that passed to getLogger() method).

The main disadvantage of such technique is that we create intermediate temporary object

that is immediately thrown away (and will be Garbage Collected) after the lines 5–6 are executed.

Syntactically, we’re creating here new anonymous inner class that inherits directly from Object using default constructor without added any new behavior (and state, of course). More rigorously, inner class definition is added at compile time. It’s value is assigned to locally scoped intermediate variable that is unreachable for “regular” code. Than, in run-time, new instance of this class is created. Because, we use this idiom inside static data members definition, it is guaranteed by the JVM, that this will happen exactly once per SomeClass class loading into the given class loader. You can think about this as implicit lock on the clinit phase, that is static block definition is guarded with the lock.

Run-time instance creation can be avoided. We can just use explicit inner class definition.

Complete example:

Local is inner class of SomeClass. So, it’s enclosing class is SomeClass. I make mini-optimization by dropping name local variable (implicit local variable is used here). Note, we don’t create any instance of Local class, we have only inner class definition (of Local class).

The main disadvantage that we have some strange entity named Local. There is no, at least easy, way to get rid of it. It takes the memory after SomeClass static initialization completed and will not be Garbage Collected as long as SomeClass.class exists.

Another disadvantage, the code looks like polluted. So, personally, I avoid this.

Now, let’s see how we can get the name of the currently executing method.

The basic ideas is:

Complete example:

name will have value foo.

That is name will have the value of “foo” that is name of currently executing method.

This trick enable you to get name of the method that you’re running in.

Hope, you enjoyed this post. 😉

Senior Software Engineer at Pursway