How to get System out console from a jar loaded by a class loader?

john :

I am running an external jar plugin like this:

  Class<?> pluginClass = pluginLoader.loadClass(".......");     
  Method main = pluginClass.getMethod("main", String[].class);
  main.invoke(null, new Object[] { new String[0] }); 

It works great. Now need to save the plugin console messages into a String

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintStream ps = new PrintStream(baos); // how to indicate System.out coming from JAR plugin 
  System.setOut(ps); 
 // how to connect ps with plugin only 

But this code saves ALL console messages into String. I don't need all application messages. How to redirect plugin only messages......messages coming from this loaded jar into the string?

Mano176 :

I made this workaround:

public class CustomPrintStream extends PrintStream {
    private String prefix;

    public CustomPrintStream(String prefix, OutputStream out) {
        super(out);
        this.prefix = prefix;
    }

    @Override
    public void println(String s) {
        if(s.startsWith(prefix))
            super.println(s);
        else {
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
            System.out.println(s);
            System.setOut(this);
        }
    }
}

This offers you the possibility to add a prefix to each of you main program's System.out.printlns, so that they get executed normally. The ones without the prefix (from your plugin) get directly into the defined out-stream (in my example the fileoutputstream)

It is used like this:

System.setOut(new CustomPrintStream("test", new FileOutputStream("C:\\out.txt"))); //Of course you can also use ByteArrayOutputStream, as you did before
System.out.println("test 1"); //this goes into the standard outstream
System.out.println("2"); //and this goes into the fileoutputstream
System.out.println("test 3");

Maybe this will help you :)

Edit: I switched it around so that the string with prefix goes into the normal outstream

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310500&siteId=1