How Do I Get The Method Name From Within That Method?
Solution 1:
return ste[1+depth].getMethodName();
If you change return statement as above, you would get immediate calling method name , of cource depth shoould be zero..
Solution 2:
Despite the fact initiating an Exception is more expensive way, I would do it anyway.
Log.d("CurrentMethod", new Exception().getStackTrace()[0].getMethodName());
Works if called in onCreate.
Solution 3:
A singleton to manage logs:
publicclassActiveLog {
publicstatic final StringTAG = "TRACE LOG";
privatestaticActiveLog instance;
privatestaticboolean actif;
publicstaticActiveLoggetInstance() {
if (null == instance)
instance = newActiveLog();
return instance;
}
privateActiveLog() {
ActiveLog.setActif(true);
}
publicvoidlog() {
if(isActif())
Log.d(TAG, "" + (newException().getStackTrace()[1].getClassName())
+ ": "
+ (newException().getStackTrace()[1].getMethodName()));
}
publicstaticbooleanisActif() {
return actif;
}
publicstaticvoidsetActif(boolean actif) {
ActiveLog.actif = actif;
}}
An example of use:
publicclassMyTest {
publicvoidtest(){
ActiveLog.getInstance().log();
}
}
The result:
09-05 14:37:09.822:D/TRACELOG(XXXX):com.TestProject.MyTest:test
Solution 4:
I think your problem maybe you are accessing the stack upside down. In the returned value element 0 is the most recent call (which would be getStackTrace()). I think what you are intending to do is:
publicstatic String getMethodName(finalint depth){
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[1 + depth].getMethodName();
}
This will access the most recent call in the stack (outside of the call to getStackTrace()). For example if you have a method:
publicvoidfoo() {
System.out.println(getMethodName(0));
}
This will print "foo" with the above implementation of the function. Of course you may also want to add some bounds checking to the function since it could easily go outside the array.
Post a Comment for "How Do I Get The Method Name From Within That Method?"