问题
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
回答1:
Example for getting the class name of the calling class in a static way from another class:
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());
}
}
Example for getting the fully qualified class name in static way:
MyClass.class.getName();
回答2:
The Java9+ technique of getting the call stack uses StackWalker
. The equivalent of Ritesh Puj's answer using StackWalker
is as follows:
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");
StackWalker.getInstance()
.walk(frames -> frames.skip(1).findFirst())
.ifPresent(frame -> {
System.out.println("I was called by a method named: " + frame.getMethodName());
System.out.println("That method is in class: " + frame.getClassName());
});
}
}
The advantage of using StackWalker
is that it generates stack frames lazily. This avoids the expense that Thread.getStackTrace()
incurs when creating a large array of stack frames. Creating the full stack trace is especially wasteful if the call stack is deep, and if you only want to look up a couple frames, as in this example.
来源:https://stackoverflow.com/questions/58224688/get-class-name-in-a-static-way-in-java-8