How to get string name of a method in java?

You can get the String like this:

Car.class.getDeclaredMethods()[0].getName();

This is for the case of a single method in your class. If you want to iterate through all the declared methods, you'll have to iterate through the array returned by Car.class.getDeclaredMethods():

for (Method method : Car.class.getDeclaredMethods()) {
    String name = method.getName();
}

You should use getDeclaredMethods() if you want to view all of them, getMethods() will return only public methods.

And finally, if you want to see the name of the method, which is executing at the moment, you should use this code:

Thread.currentThread().getStackTrace()[1].getMethodName();

This will get a stack trace for the current thread and return the name of the method on its top.


Since methods aren't objects themselves, they don't have direct properties (like you would expect with first-class functions in languages like JavaScript).

The closest you can do is call Car.class.getMethods()

Car.class is a Class object which you can use to invoke any of the reflection methods.

However, as far as I know, a method is not able to identify itself.


So, you want to get the name of the currently executing method? Here's a somewhat ugly way to do that:

Exception e = new Exception();
e.fillInStackTrace();
String methodName = e.getStackTrace()[0].getMethodName();

Look into this thread:

Getting the name of the currently executing method

It offers some more solutions - for example:

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