How do I find the caller of a method using stacktrace or reflection?

后端 未结 12 1150
鱼传尺愫
鱼传尺愫 2020-11-21 13:26

I need to find the caller of a method. Is it possible using stacktrace or reflection?

12条回答
  •  不知归路
    2020-11-21 13:45

    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    class DBConnection {
        String createdBy = null;
    
        DBConnection(Throwable whoCreatedMe) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PrintWriter pw = new PrintWriter(os);
            whoCreatedMe.printStackTrace(pw);
            try {
                createdBy = os.toString();
                pw.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public class ThrowableTest {
    
        public static void main(String[] args) {
    
            Throwable createdBy = new Throwable(
                    "Connection created from DBConnectionManager");
            DBConnection conn = new DBConnection(createdBy);
            System.out.println(conn.createdBy);
        }
    }
    

    OR

    public static interface ICallback { T doOperation(); }
    
    
    public class TestCallerOfMethod {
    
        public static  T callTwo(final ICallback c){
            // Pass the object created at callee to the caller
            // From the passed object we can get; what is the callee name like below.
            System.out.println(c.getClass().getEnclosingMethod().getName());
            return c.doOperation();
        }
    
        public static boolean callOne(){
            ICallback callBackInstance = new ICallback(Boolean){
                @Override
                public Boolean doOperation() 
                {
                    return true;
                }
            };
            return callTwo(callBackInstance);
        }
    
        public static void main(String[] args) {
             callOne();
        }
    }
    

提交回复
热议问题