Как автоматически добавлять имена классов и функций в мой журнал - PullRequest
4 голосов
/ 29 марта 2012

Я использую android.util.Log

class Foo
{
  private void boo()
  {
    // This is the basic log of android.
    Log.i("tag", "Start");
  }
}

Я хочу, чтобы журнал печатался [Foo::boo] Start.
Могу ли я получить имя класса и функции в Java? Тогда как мне обернуть код?

Ответы [ 3 ]

5 голосов
/ 29 марта 2012

здесь ОБНОВЛЕНО

String tag = "[";
tag += this.getClass().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");

this.getClass().toString() вернет имя класса в виде строки

ОБНОВЛЕНИЕ

если функцияstatic, затем используйте следующий код

String tag = "[";
tag += Thread.currentThread().getStackTrace()[1].getClassName().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");
2 голосов
/ 29 марта 2012

Получить текущее имя класса и имя функции:

Log.i(getFunctionName(), "Start");

private String getFunctionName()    
    {    
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();    
        if(sts == null)    
        {    
            return null;    
        }    
        for(StackTraceElement st : sts)    
        {    
            if(st.isNativeMethod())    
            {    
                continue;    
            }    
            if(st.getClassName().equals(Thread.class.getName()))    
            {    
                continue;    
            }    
            if(st.getClassName().equals(this.getClass().getName()))    
            {    
                continue;    
            }    
            return mClassName + "[ " + Thread.currentThread().getName() + ": "    
                    +  " "   + st.getMethodName() + " ]";    
        }    
        return null;    
    }    
1 голос
/ 29 марта 2012

Вы можете использовать эти методы java.lang.Class class

getClass().getname() - to get the name of the class
getClass().getMethods() - to get the methods declared in that class.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...