Java separate System.out for separate Classpath

社会主义新天地 提交于 2019-12-11 05:25:36

问题


I am developing an application which needs to call some Jenkins instances, to do this I am using the jenkins-cli .jar
I could be calling the jar using the commandline to easily extract its output. Then however I need to parse exceptions myself.
To properly handle exceptions I am now invoking the main method of the jar via reflection:

URLClassLoader jenkinsClassloader = new URLClassLoader(new URL[]{"UrlToJenkins-Cli.jar"}, getClass().getClassLoader());
Class<?> jenkinsCli = Class.forName ("hudson.cli.CLI", false, jenkinsClassloader);
Method mainMethod = jenkinsCli.getDeclaredMethod("main", String[].class);
mainMethod.invoke (null, (Object) commandArray);

But now I need to somehow get the output the jar prints to System.out
I know I can use System.setOut(). The problem there is that I have other threads logging simultaniously. I read here that System.out is classloader specific, but I couldn't find any additional information about this.
Does someone know a way to get the stdout of the jar without it being interfered with from other threads?


回答1:


One possibility would be to create a custom class extending PrintStream, that would simply pass whatever is passed to it to another PrintStream, then wrap that around System.out, via System.setOut(); the custom class could have a ThreadLocal private attribute that could be used to tell it if, for the current thread, the text should be intercepted.

Not the most elegant of solutions, but could be a good fallback if no alternative is found.



来源:https://stackoverflow.com/questions/43471635/java-separate-system-out-for-separate-classpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!