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

后端 未结 12 1571
鱼传尺愫
鱼传尺愫 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:39

    private void parseExceptionContents(
          final Exception exception,
          final OutputStream out)
       {
          final StackTraceElement[] stackTrace = exception.getStackTrace();
          int index = 0;
          for (StackTraceElement element : stackTrace)
          {
             final String exceptionMsg =
                  "Exception thrown from " + element.getMethodName()
                + " in class " + element.getClassName() + " [on line number "
                + element.getLineNumber() + " of file " + element.getFileName() + "]";
             try
             {
                out.write((headerLine + newLine).getBytes());
                out.write((headerTitlePortion + index++ + newLine).getBytes() );
                out.write((headerLine + newLine).getBytes());
                out.write((exceptionMsg + newLine + newLine).getBytes());
                out.write(
                   ("Exception.toString: " + element.toString() + newLine).getBytes());
             }
             catch (IOException ioEx)
             {
                System.err.println(
                     "IOException encountered while trying to write "
                   + "StackTraceElement data to provided OutputStream.\n"
                   + ioEx.getMessage() );
             }
          }
       }
    

提交回复
热议问题