Karan
Karan

Reputation: 1

How can a Java method retrieve the method object pertaining to that particular method? (Java)

I am writing a Java method with the following signature.

void Logger(Method method, Object[] args);

If a method (e.g. ABC() ) calls this method Logger, it should retrieve the Method object that encapsulates data about itself (ABC()) and pass it as an argument.

How can a method retrieve the Method object that is storing all the information about that method?

A simple way is that I use Method[] methods = ExampleClass.Class.getMethods(); and search the whole array for the Method with the correct name. (Which is quite inefficient). Also, if two or more methods have the same names, then I will have to retrieve their parameter types too (to distinguish them) and have different code for each method. This would be inefficient as well as painful.

Is there a better way?

Thanks for the help.

Upvotes: 0

Views: 762

Answers (3)

madhurtanwani
madhurtanwani

Reputation: 1219

If you are writing a wrapper over existing logger frameworks then the already provide a way to print the method name in the log message - if that's what you are trying to implement.

You can read from the log4j documentation, for example, that this extraction (as the other answer suggests) is done from the stack trace and is expensive : http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

Upvotes: 0

Avi
Avi

Reputation: 20142

Even better, don't implement this method at all. Use logback, or some other modern logging framework.

Upvotes: 1

BalusC
BalusC

Reputation: 1108742

Don't do it. Rather obtain the method name from the stack.

public void log(Object object) {
    String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
    // ...
}

This is however pretty expensive and that's why most self-respected logging frameworks offer an option to turn it on/off (which I would recommend to use instead of homegrowing one).

Upvotes: 5

Related Questions