在实例方法中如何获取该方法所属的类名、方法名、行数呢?
例子项目有两个类:
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();