title: Capture Console Output of a Specific Thread in Java
body: <p>I realize there are similar questions on SO, but they don't quite solve my problem.</p>
  
  <p>I would like a method that, given a Class object, will invoke the "main" method, that is to say, public static void main, on that Class (if it exists) and capture the console output of that main method.  The class doing the invocation is a non-daemon thread.</p>
  
  <p>I have part of the code already, but I'm not sure how to capture the console output, and on top of that, how to only capture it for *this specific thread.  Here's what I have so far:</p>
  
  <pre><code>public class Output extends Thread {
      private Class testClass;
  
      public Output(Class clazz) {
          this.testClass = clazz;
      }
  
      private Method getMainMethod(Class clazz) {
          Method[] methods = clazz.getMethods();
          for (Method method : methods) {
              if (isMainMethod(method)) { 
                  return method;
              }
          }
  
          return null;
      }
  
      private Boolean isMainMethod(Method method) {
          return (method.getName().equals("main") &amp;&amp;
                  Modifier.isStatic(method.getModifiers()) &amp;&amp;
                  method.getReturnType().equals(Void.class));
      }
  
      public void run() {
          Method mainMethod = null;
  
          if ((mainMethod = getMainMethod(this.testClass)) == null) {
              //if there's no static void main method, throw exception
              throw new YouFuckedItUpException();
          }
  
          mainMethod.invoke(this.testClass, new String[0]);
  
          return heresWhereImStuckIWantToCaptureTheConsoleOutputAndReturnIt();
      }
  }
  </code></pre>
  
  <p>All I need is some code to, or a link to an answer on how to, capture the System.out and System.err output of the method being invoked.  Any help someone can give would be much appreciated.</p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>EDIT:</strong> This is NOT for testing only, this will eventually be something put into production.</p>
  
  <p><strong>EDIT 2</strong>: This will need to be thread-safe.  Multiple main methods will be invoked by other threads possibly at the same time, and I want each thread to only capture its own specific output.</p>