If you want to automatically print mainactivity.oncreate (line:37) This class name in your Android program. How does the log of the method name (number of rows) be implemented?
1. The Java-introduced line Cheng Stacks Java.lang package provides a stacktraceelement that 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 array holds the method of executing the call in the thread. 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 are printed as follows:
Observing the output shows that the method in the stack is first performed 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;}
The customtagprefix is a custom prefix. 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.
Design Android log module with line Cheng stacks stacktraceelement