开发者

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.


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).


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜