Suppose you want a class name such as the active print program Mainactivity.oncreate (line:37) on your Android. Method name (line) How do I sign in?
1. Describes the Java thread execution stack Java.lang package that provides stacktraceelement, which can be used to get the call stack information for a method.
By calling the thread function Thread.CurrentThread (). Getstacktrace () can get a stack array of stacktraceelement[]. The method that runs the call in the thread is saved in the array. Observe the following code:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); stacktraceelement[] StackTrace = Thread.CurrentThread (). Getstacktrace (); System.out.println ("Call OnCreate method"); System.out.println ("StackTrace len:" + stacktrace.length); for (int i = 0; i < stacktrace.length; i++) {System.out.println ("----the " + i + "element ----"); System.out.println ("toString:" + stacktrace[i].tostring ()); System.out.println ("ClassName:" + stacktrace[i].getclassname ()); System.out.println ("FileName:" + stacktrace[i].getfilename ()); System.out.println ("linenumber:" + stacktrace[i].getlinenumber ()); System.out.println ("MethodName:" + stacktrace[i].getmethodname ());}}
Call the Getstacktrace method in the OnCreate method to get the information for the call stack. The results of the printing are as follows:
Observing the output shows that the method that runs first in the stack is the method in the VM and thread. The 3rd is the method you are calling (the method that calls Getstacktrack).
2. Log module DesignGenerate tag:
private static String Generatetag (Stacktraceelement stack) {string tag = "%s.%s (l:%d)"; String className = Stack.getclassname (); className = classname.substring (Classname.lastindexof (".") +1); tag = String.Format (tag, Stack.getclassname (), Classname,stack.getlinenumber ()); tag = Customtagprefix==null?tag:customtagprefix+ ":" +tag;return Tag;}
Customtagprefix is a prefix that is defined by itself. Packing LOG:
public static void D (String content) {if (!allowd) {return;} Stacktraceelement caller = Thread.CurrentThread (). Getstacktrace () [3]; String tag = Generatetag (caller); LOG.D (tag, content);} public static void D (String content,throwable thr) {if (!allowd) {return;} Stacktraceelement caller = Thread.CurrentThread (). Getstacktrace () [3]; String tag = Generatetag (caller); LOG.D (tag, content,thr);}
Getstacktrace () [3], the reason for taking fourth is the first two methods of VM and thread respectively, subscript 2 is the current D () method, and the subscript of the method that calls D () is 3.
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Designing the Android Log module using the thread execution stack stacktraceelement