zoukankan      html  css  js  c++  java
  • java 获取当前方法的被调用信息(被那个方法那个类那一行调用)

    public void testMethod(){
            
            Test1 t1 = new Test1();
            t1.my();
            
        }
        
        public static void main(String[] args) {
            Test t = new Test();
            t.testMethod();
        }
        
         class Test1{
            public void my(){
                
                
                String  tag = this.getMyGrandpaStackTrace();
                System.err.println(String.format("调用我的人是:%s", tag));
            }
             
             
             public String  getMyGrandpaStackTrace(){
                    
                 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                     StackTraceElement father = stackTrace[1];
                    StackTraceElement log = stackTrace[2];
                    String tag = null;
                    for (int i = 1; i < stackTrace.length; i++) {
                        StackTraceElement e = stackTrace[i];
                        if (!e.getClassName().equals(log.getClassName())) {
                            tag = e.getClassName() + "." + e.getMethodName();
                            break;
                        }
                    }
                    if (tag == null) {
                        tag = log.getClassName() + "." + log.getMethodName();
    
                    }
                    System.err.println(String.format("My father  is %s.%s", father.getClassName() ,father.getMethodName()));
                    System.err.println(String.format("My grandpa is %s",tag));
                    return tag;
        
                }
            
        }
  • 相关阅读:
    快速排序
    fedora 配置
    while与do while
    switch选择结构
    if选择结构
    java有参
    java猜拳
    java类的无参方法
    java类与对象
    java数组
  • 原文地址:https://www.cnblogs.com/JavaHxm/p/10985705.html
Copyright © 2011-2022 走看看