Java单独的System.out用于单独的类路径 [英] Java separate System.out for separate Classpath
问题描述
我正在开发一个需要调用某些Jenkins实例的应用程序,为此,我正在使用jenkins-cli .jar
我可能使用命令行调用jar来轻松提取其输出.然后,我需要自己解析异常.
为了正确处理异常,我现在通过反射调用jar的主要方法:
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);
但是现在我需要以某种方式将jar打印的输出输出到System.out
我知道我可以使用System.setOut()
.那里的问题是我有其他线程同时记录.
我阅读了这里 System.out是特定于类加载器的,但是我找不到关于此的任何其他信息.
有人知道一种在不受到其他线程干扰的情况下获取jar的stdout的方法吗?
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?
推荐答案
一种可能是创建扩展 ThreadLocal
私有属性,可用于告诉它对于当前线程是否应截取文本.
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.
这篇关于Java单独的System.out用于单独的类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!