Java:获取当前函数所属类的类名


#Java 笔记


方式1: 非静态方法中使用 this.getClass().getName()

public class ClassNameTest {

	public void testMethod() {
		System.out.println(this.getClass().getName());
	}

	public static void main(String[] args) {
		ClassNameTest classNameTest = new ClassNameTest();
		classNameTest.testMethod();
	}
}

方式2: 使用函数内部类/匿名类对象的 getEnclosingClass 方法

public class ClassNameTest {

	public static void testMethod() {
		String className = new Object() {}
				.getClass()
				.getEnclosingClass()
				.getName();
		System.out.println(className);
	}

	public static void main(String[] args) {
		testMethod();
	}

}

运行结果:

ClassNameTest

方式3: 从异常堆栈跟踪中获取方法名

public class ClassNameTest {

	public static void testMethod() {
		StackTraceElement[] stackTrace = new Throwable().getStackTrace();
		String className = stackTrace[0].getClassName();
		System.out.println(className);
	}

	public static void main(String[] args) {
		testMethod();
	}

}

运行结果:

ClassNameTest

方式4: 从线程堆栈跟踪中获取方法名

public class ClassNameTest {

	public static void testMethod() {
		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		String className = stackTrace[1].getClassName();
		System.out.println(className);
	}

	public static void main(String[] args) {
		testMethod();
	}
}

运行结果:

ClassNameTest


( 本文完 )