以下是案例,已运行通过
1 package com.hdys; 2 /* 3 * 1.获取当前运行代码的类名,方法名,主要是通过java.lang.StackTraceElement类 4 * 5 * 2. 6 * [1]获得调用者的方法名, 同new Throwable 7 * String _methodName = new Exception().getStackTrace()[1].getMethodName(); 8 * [0]获得当前的方法名, 同new Throwable 9 * String _thisMethodName = new Exception().getStackTrace()[0].getMethodName(); 10 * 11 * 3.获取当前类名的全称和简称,还可以使用 this.getClass() 12 * (1)获取当前类名的简称 13 * String simpleClassName = this.getClass().getSimpleName(); 14 * (2)获取当前类名的完整名称 15 * String className = this.getClass().getName(); 16 * */ 17 public class parent { 18 19 public static void main(String[] args) { 20 parent t=new parent(); 21 System.out.println("---------获取方法名--------------"); 22 t.getMethodNameTest(); 23 System.out.println("---------获取类名--------------"); 24 child c = new child(); 25 System.out.println("---------仅获取当前类名--------------"); 26 t.getClassNameTest(); 27 } 28 29 //仅获取当前类名 30 public void getClassNameTest(){ 31 System.out.println("完整类名:"+this.getClass().getName()); 32 System.out.println("简单类名:"+this.getClass().getSimpleName()); 33 //System.out.println("父类名 :"+this.getClass().getSuperclass()); 34 } 35 36 //获取方法名 37 public void getMethodNameTest(){ 38 String _thisMethodName = new Exception().getStackTrace()[0].getMethodName(); 39 System.out.println("获得当前的方法名:"+_thisMethodName); 40 41 String _methodName = new Exception().getStackTrace()[1].getMethodName(); 42 System.out.println("获得调用者的方法名:"+_methodName); 43 } 44 }