Search code examples
javajava-8staticclassname

Get class name in a static way in Java 8


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


Solution

  • 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();