This is a follow up to more general and similar question/answers
In Java 8 I can get class name called the method using new Exception
String className = new Exception().getStackTrace()[1].getClassName();
But can I get class name in a static way?
edit
If I'm inside a different class's method and want to know the class called my method
public class Main {
public static void main(String[] args) {
example();
}
public static void example() {
B b = new B();
b.methodB();
}
}
class B {
public void methodB(){
System.out.println("I am methodB");
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement element = stackTrace[2];
System.out.println("I was called by a method named: " + element.getMethodName());
System.out.println("That method is in class: " + element.getClassName());
}
}
MyClass.class.getName();