Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

reflection - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...