Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string name of a method in java?

How can I find out through reflection what is the string name of the method?

For example given:

class Car{    public void getFoo(){    } } 

I want to get the string "getFoo", something like the following:

 Car.getFoo.toString() == "getFoo" // TRUE 
like image 717
Andriy Drozdyuk Avatar asked Jun 11 '10 13:06

Andriy Drozdyuk


People also ask

How do you call a method name in Java?

Call a MethodInside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"

What is getClass () getName () in Java?

The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.


2 Answers

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.

like image 80
Malcolm Avatar answered Oct 11 '22 22:10

Malcolm


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.

like image 39
Matt Avatar answered Oct 11 '22 21:10

Matt