Get class name in a static way in Java 8 [duplicate]

匆匆过客 提交于 2021-02-07 10:12:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!