Java中查看一个方法被调用的层次(Reflection、StackTrace)

package test;

public class Main {
    public static void main(String[] args) {
        new Test().test();
    }
}

package test;

import java.util.Map;
import sun.reflect.Reflection;

public class Test {
    public void test() {
        System.out.println("------------Reflection.getCallerClass(i)------------");
        System.out.println("Reflection.getCallerClass(0)=" + Reflection.getCallerClass(0));
        System.out.println("Reflection.getCallerClass(1)=" + Reflection.getCallerClass(1));
        System.out.println("Reflection.getCallerClass(2)=" + Reflection.getCallerClass(2));
        System.out.println("Reflection.getCallerClass(3)=" + Reflection.getCallerClass(3));
        System.out.println("Reflection.getCallerClass(4)=" + Reflection.getCallerClass(4));

        System.out.println("\n------------new Throwable().getStackTrace()------------");
        StackTraceElement[] elements = new Throwable().getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            System.out.println(elements[i]);
        }

        System.out.println("\n------------Thread.currentThread().getStackTrace()------------");
        elements = Thread.currentThread().getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            System.out.println(elements[i]);
        }

        System.out.println("\n------------Thread.getAllStackTraces()------------");
        Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
        elements = map.get(Thread.currentThread());
        for (int i = 0; i < elements.length; i++) {
            System.out.println(elements[i]);
        }
    }

}

运行结果:

------------Reflection.getCallerClass(i)------------
Reflection.getCallerClass(0)=class sun.reflect.Reflection
Reflection.getCallerClass(1)=class test.Test
Reflection.getCallerClass(2)=class test.Main
Reflection.getCallerClass(3)=null
Reflection.getCallerClass(4)=null

------------new Throwable().getStackTrace()------------
test.Test.test(Test.java:33)
test.Main.main(Main.java:5)

------------Thread.currentThread().getStackTrace()------------
java.lang.Thread.getStackTrace(Thread.java:1426)
test.Test.test(Test.java:39)
test.Main.main(Main.java:5)

------------Thread.getAllStackTraces()------------
java.lang.Thread.dumpThreads(Native Method)
java.lang.Thread.getAllStackTraces(Thread.java:1477)
test.Test.test(Test.java:45)
test.Main.main(Main.java:5)

你可能感兴趣的:(java,thread,sun)