在成員方法中獲取類名、方法名、行數
在實例方法中如何獲取該方法所屬的類名、方法名、行數呢?
例子項目有兩個類:
package com.jn.bean;
public class Student {
public String method2(int age,String name) {
System.out.println("execute....");
Class clazz = this.getClass();
String className = clazz.getCanonicalName();/* com.jn.bean.Student */
String classSimpleName = clazz.getSimpleName();
Object[] objs = clazz.getSigners();
//當前的線程
Thread currentThread=Thread.currentThread();
//當前的線程名稱
String threadName =currentThread .getName();
StackTraceElement stackElement=currentThread.getStackTrace()[1];
//當前的方法名
String methodName=stackElement.getMethodName();
//當前的文件名
String filename=stackElement.getFileName();
int lineNum=stackElement.getLineNumber();
System.out.println("class name:\t\t" + className);
System.out.println("class simple name:\t" + classSimpleName);
System.out.println("thread name:\t\t" + threadName);
System.out.println("method name:\t\t"+methodName);
System.out.println("file name:\t\t"+filename);
System.out.println("line number:\t\t"+lineNum);
System.out.println("----------------------------------\n");
System.out.println("objs:" + objs);
if (objs != null) {
for (int i = 0; i < objs.length; i++) {
Object object = objs[i];
System.out.println(object);
}
}
return "success";
}
}
package com.jn.main;
import com.jn.bean.Student;
public class Main2 {
public static void main(String[] args) {
Student student=new Student();
student.method2(1,null);
}
}
運行結果:
項目結構如下:
總結:
(1)在實例方法中獲取類名
Class clazz = this.getClass();//因為是實例方法,所以可以用this
String className = clazz.getCanonicalName();/* com.jn.bean.Student */
String classSimpleName = clazz.getSimpleName();
(2)獲取方法名
//當前的線程
Thread currentThread=Thread.currentThread();
StackTraceElement stackElement=currentThread.getStackTrace()[1];
//當前的方法名
String methodName=stackElement.getMethodName();
(3)獲取當前行數
//當前的線程
Thread currentThread=Thread.currentThread();
StackTraceElement stackElement=currentThread.getStackTrace()[1];
int lineNum=stackElement.getLineNumber();
最後更新:2017-04-03 12:54:03