How to get method name for debug output in Android/Java?

自闭症网瘾萝莉.ら 提交于 2019-12-24 19:08:59

问题


I would like to make a macro that prints out the current method's name during Log.d and Log.e output. Right now I simply type the method name within a hard-coded string, but this is obviously inefficient should the method name change in the future, as each string needs to be searched for and replaced.

I am aware of using getMethodName() as indicated in this post:

How to get method name in Java

This one also looks promising:

Debugging with helper extension method

There are countless numbers of these posts on SO, but I'd like to find the best way for debugging purposes that does not impact runtime performance too much. Since I am using Eclipse I would like to find a solution that works well with that IDE.


回答1:


This is what I know of that is available to you for the current execution.

    Thread current = Thread.currentThread();
    StackTraceElement[] stack = current.getStackTrace();
    for(StackTraceElement element : stack)
    {
        if (!element.isNativeMethod()) {
            String className = element.getClassName();
            String fileName = element.getFileName();
            int lineNumber = element.getLineNumber();
            String methodName = element.getMethodName();
        }
    }



回答2:


this is a simple yet very useful eclipse plug-in i mentioned in the comment above: download plugin

its an incremental builder so typical build time is measured in fractions of seconds. add it to your .project file as a new builder <buildCommand> with name:

<name>org.pskink.logger.builder</name>

it should be the last builder in <buildSpec> list

installation: just copy it to plugins folder and restart eclipse



来源:https://stackoverflow.com/questions/17074073/how-to-get-method-name-for-debug-output-in-android-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!