public class ClassNameTest {
public void testMethod() {
System.out.println(this.getClass().getName());
}
public static void main(String[] args) {
ClassNameTest classNameTest = new ClassNameTest();
classNameTest.testMethod();
}
}
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
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
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
( 本文完 )