How to get string name of a method in java?

前端 未结 7 706
梦谈多话
梦谈多话 2020-11-29 06:10

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

For example given:

class Car{
   public void getFoo(){
   }
}

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 06:17

    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.

提交回复
热议问题