获取当前运行代码的类名,方法名,行号
2013-04-10 13:16
555 查看
/* * 1.获取当前运行代码的类名,方法名,行号,主要是通过java.lang.StackTraceElement类 * * 2. * [1]获得调用者的方法名, 同new Throwable * String _methodName = new Exception().getStackTrace()[1].getMethodName(); * [0]获得当前的方法名, 同new Throwable * String _thisMethodName = new Exception().getStackTrace()[0].getMethodName(); * */ public class StackTraceElementTest { public static void main(String[] args) { System.out.println("line1: " + new Throwable().getStackTrace()[0].getLineNumber()); System.out.println("line2: " + getLineInfo()); System.out.println("line3: " + getTraceInfo()); StackTraceElement ste1 = null; StackTraceElement[] steArray = Thread.currentThread().getStackTrace(); int steArrayLength = steArray.length; String s = null; // output all related info of the existing stack traces if(steArrayLength==0) { System.err.println("No Stack Trace."); } else { for (int i=0; i<steArrayLength; i++) { System.out.println("Stack Trace-" + i); ste1 = steArray[i]; s = ste1.getFileName() + ": Line " + ste1.getLineNumber(); System.out.println(s); } } } public static String getTraceInfo(){ StringBuffer sb = new StringBuffer(); StackTraceElement[] stacks = new Throwable().getStackTrace(); int stacksLen = stacks.length; sb.append("class: " ).append(stacks[1].getClassName()) .append("; method: ").append(stacks[1].getMethodName()) .append("; number: ").append(stacks[1].getLineNumber()); return sb.toString(); } public static String getLineInfo() { StackTraceElement ste = new Throwable().getStackTrace()[1]; return ste.getFileName() + ": Line " + ste.getLineNumber(); } }
相关文章推荐
- Java中获取当前运行代码的类名、方法名、行号
- Java中获取当前运行代码的类名、方法名、行号
- Java中获取当前运行代码的类名、方法名、行号
- python_获取当前代码行号_获取当前运行的类名和函数名的方法
- 获取当前运行代码的类名,方法名,行号
- Java中获取当前运行代码的类名、方法名、行号
- python 动态获取当前运行的类名和函数名的方法
- 获取当前运行的类名或者方法
- Java中获取运行代码的类名、方法名
- Android获取当前运行的类名或者方法
- JAVA中获取当前运行的类名,方法名,行数
- c#获取当前代码运行的文件名、运行的函数名以及当前代码执行的行号
- python获取当前运行函数名称的方法实例代码
- python 动态获取当前运行的类名和函数名的方法
- Java编程实现获取当前代码行行号的方法示例
- JAVA中获取当前运行的类名,方法名,行数
- 获取当前方法名,行号,类名,所在java文件第几行
- JAVA中如何动态获取得当前的文件名/类名/方法名/行号
- Java: 获取当前执行位置的文件名/类名/方法名/行号
- C#获取当前程序运行路径的方法集合